/*
	Get Colors from: http://www.psyclops.com/tools/rgb/
	Get Samp Functions from: http://wiki.sa-mp.com/wiki/Category:Scripting_Functions
	Get Callbacks from: http://wiki.sa-mp.com/wiki/Category:Scripting_Callbacks
	
	For other help and plugins try: Samp froums
	
	- Added Weapon Menu
	    Components:
			ShowPlayerWeaponMenu(playier, team);
			Weapon Dialog
			Weapon Limit (WeaponLimit)
			How many times the weapon is picked (TimesPicked)
			Which Weapon did the player pick/had (Player[playerid][WeaponPicked])
			Load weapon limits from config
			Reduce the number of times the weapon was pick in OnPlayerDeath
			Added text color as a variables (TextColor)
			Defined weapons names
		-
	-
	
	- On Player Take Damage
	    Components:
	        ILost
	        Declared
	        HPLost
	        H
	        TakeDmgCD
	        DoingDamage Textdraw
	        GettingDamaged Textdraw
		-
	-
	


	- Vehicle Nitro
	- OnPlayerStreamIn and Out
	- ColorFix
	- RadarFix
	- TeamHP, PlayersAlive, TeamName
	- OnPlayerEnterCheckPoint and OnPlayerExitCheckPoint
	- Round Mints, Round Seconds, Config Round Time.
	- OnPlayerDisconnect Reasons.


	Next:
	
	- StartSpecated, StopSpectated, SpectateNextPlayer, SpectatePreviousPlayer

*/

#include <a_samp> // Most samp functions (e.g. GetPlayerHealth and etc)
#include <foreach> // Used to loop through all connected players
#include <zcmd> // Used for commands.
#include <dini> // Used to store, write and get data to/from .ini files (in scriptfiles)
#include <sscanf2> // Just read on it

native WP_Hash(buffer[], len, const str[]); // Used to convert your password to a code

#define NON 			0 // Team nothing, used for when the player join the server
#define ATTACKER 		1 // Attacker team
#define DEFENDER 		2 // Defender team
#define REFEREE 		3 // Referee team
#define ATTACKER_SUB 	4 //
#define DEFENDER_SUB 	5


#define ATTACKER_PLAYING 		0xFF000055 // Bright red color with 55 transparency (Range 00 - 99 - FF)
#define ATTACKER_NOT_PLAYING 	0xFF444455 // Orange red color
#define ATTACKER_SUB_COLOR 		0xFF888855 // Yello red color
#define DEFENDER_PLAYING 		0x0000FF55 // Bright blue color
#define DEFENDER_NOT_PLAYING 	0x4444FF55 // Light blue color
#define DEFENDER_SUB_COLOR		0x8888FF55 // Very light blue color
#define REFEREE_COLOR 			0xFFFF0055 // Bright Yellow color

#define KNIFE           4
#define SILENCER        23
#define DEAGLE          24
#define SHOTGUN         25
#define COMBAT          27
#define MP5             29
#define AK47            30
#define M4              31
#define RIFLE           33
#define SNIPER          34

#define MAX_BASES 		80
#define MAX_TEAMS 		6
#define MAX_DMS 		15
#define SAVE_SLOTS      10

#define DIALOG_WEAPONS_TYPE     1
#define DIALOG_CURRENT_TOTAL    2
#define DIALOG_TEAM_SCORE       3
#define DIALOG_ATT_NAME         4
#define DIALOG_DEF_NAME         5
#define DIALOG_ATT_SCORE        6
#define DIALOG_DEF_SCORE        7


#define CONFIG_PATH "attackdefend/config.ini"

#define PRESSED(%0) (((newkeys & (%0)) == (%0)) && ((oldkeys & (%0)) != (%0)))

#undef MAX_PLAYERS
#define MAX_PLAYERS      50

// - Global Textdraws -
// If you want to give the text itself a color then get colors from: http://wiki.sa-mp.com/wiki/Colors_List
	
new Text: AttackerText; // Attacker (OnPlayerRequestClass) textdraw
new Text: DefenderText; // Defender (OnPlayerRequestClass) textdraw
new Text: RefereeText; // Referee (OnPlayerRequestClass) textdraw
new Text: RoundStats; // Shows team names, players alive and team hp.
new Text: RoundsPlayed; // Shows how many rounds are played out of for example 9 rounds. (Rounds 3/9)
new Text: TeamScoreText; // Shows team name and score (e.g. TeK 3 CZE 3)
new Text: BaseID_VS;

	// -EndRound TextDraw
new Text: EN_Attacker;
new Text: EN_Defender;
new Text: EN_WhoWon;
new Text: EN_AttackerDefenderTitle;
new Text: EN_AttackerList;
new Text: EN_AttackerKills;
new Text: EN_AttackerDeaths;
new Text: EN_AttackerDamage;
//new Text: EN_BaseID;
new Text: EN_DefenderList;
new Text: EN_DefenderKills;
new Text: EN_DefenderDeaths;
new Text: EN_DefenderDamage;



// - Player Textdraws -

new PlayerText: FPSPingPacket[MAX_PLAYERS]; // Ping, FPS and Packetloss textdraw on top right corner.
new PlayerText: RoundKillDmgTDmg[MAX_PLAYERS]; // Shows Kills, Damage and Total Damage on the left hand side of the radar.
new PlayerText: DoingDamage[3][MAX_PLAYERS]; // Shows when player hit someone.
new PlayerText: GettingDamaged[3][MAX_PLAYERS]; // Shows when someone hit you.
new PlayerText: RoundText[MAX_PLAYERS]; // Shows round start time.
new PlayerText: WhoSpec[2][MAX_PLAYERS]; // Shows who is spectating you.
new PlayerText: SpecText[2][MAX_PLAYERS]; // Shows spectated player info.

// - Player Variables -

enum PlayerVariables {
	Name[MAX_PLAYER_NAME],
	NameWithoutTag[MAX_PLAYER_NAME],
	bool:Logged,
	bool:IgnoreSpawn,
	bool:InDM,
	bool:Syncing,
	bool:Playing,
	bool:WasInCP,
	bool:IsKicked,
	bool:Spectating,
	bool:BeingSpeced,
	bool:CalledByPlayer,
	bool:WasInBase,
	bool:TextDrawOnScreen,
	IsSpectatingID,
	Level,
	Weather,
	Time,
	Team,
	DLlast,
	FPS,
	Float:pHealth,
	Float:pArmour,
	DMReadd,
	RoundKills,
	RoundDeaths,
	Float:RoundDamage,
	TotalKills,
	TotalDeaths,
	Float:TotalDamage,
	WeaponPicked
	
}
new Player[MAX_PLAYERS][PlayerVariables];

enum save_vars
{
	pName[24],
	Float:gHealth,
	Float:gArmour,
	pWeapons[13],
	pAmmo[13],
	pTeam,
	pSkin,
	pInterior,
	pVWorld,
	Float:pCoords[4],
	Float:RDamage,
	Float:TDamage,
	RKills,
	TKills,
	RDeaths,
	TDeaths,
	RoundID,
}
new SaveVariables[SAVE_SLOTS][save_vars];

enum rankingEnum {
    player_Score,
    player_ID
}

// - Base Variables -

new Float:AttackerSpawn[MAX_BASES][3];
new Float:DefenderSpawn[MAX_BASES][3];
new Float:CPSpawn[MAX_BASES][3];
new BInterior[MAX_BASES];
new BName[MAX_BASES][128];
new bool:BExist[MAX_BASES] = false;

// - DM Variables -

new Float:DMSpawn[MAX_DMS][4];
new DMInterior[MAX_DMS];
new DMWeapons[MAX_DMS][3];
new bool:DMExist[MAX_DMS] = false;

// - Config Variables -

new MainWeather; // Server start up weather
new MainTime; // Server start up time
new ConfigCPTime;
new ConfigRoundTime;
new Float:MainSpawn[4];
new MainInterior;
new TotalRounds;

new Skin[MAX_TEAMS];
new TextColor[MAX_TEAMS][10];
new TDC[MAX_TEAMS][5];

// - Global Strings -

new ChatString[128];
//new BasesPlayed[256];

// - boolen variables

new bool:AllowStartBase = true;

// - Numerical Variables

new ViewTimer;
new CurrentCPTime;
new HighestID;

// - Round Variables

new bool:BaseStarted = false;
new bool:RoundPaused = false;
new bool:WarMode = false;

new Current = -1;
new WeaponLimit[10];
new TimesPicked[3][10];
new PlayersAlive[3];
new Float:TeamHP[3];
new TeamName[3][24];
new PlayersInCP;
new RoundMints;
new RoundSeconds;
new GameType;
new CurrentRound;
new TeamScore[3];

// - OnPlayerTakeDamage Variables

new bool:Declared[4][MAX_PLAYERS];
new gLastHit[6][MAX_PLAYERS];
new TakeDmgCD[9][MAX_PLAYERS];
new H[6][MAX_PLAYERS];
new Float:HPLost[2][MAX_PLAYERS][MAX_PLAYERS];
new Float:ILost[MAX_PLAYERS];

new WeaponNames[55][] =
{
        {"Punch"},{"Brass Knuckles"},{"Golf Club"},{"Nite Stick"},{"Knife"},{"Baseball Bat"},{"Shovel"},{"Pool Cue"},{"Katana"},{"Chainsaw"},{"Purple Dildo"},
        {"Smal White Vibrator"},{"Large White Vibrator"},{"Silver Vibrator"},{"Flowers"},{"Cane"},{"Grenade"},{"Tear Gas"},{"Molotov Cocktail"},
        {""},{""},{""}, // Empty spots for ID 19-20-21 (invalid weapon id's)
        {"9mm"},{"Silenced 9mm"},{"Deagle"},{"Shotgun"},{"Sawn-off"},{"Combat"},{"Micro SMG"},{"MP5"},{"AK-47"},{"M4"},{"Tec9"},
        {"Rifle"},{"Sniper"},{"Rocket"},{"HS Rocket"},{"Flamethrower"},{"Minigun"},{"Satchel Charge"},{"Detonator"},
        {"Spraycan"},{"Fire Extinguisher"},{"Camera"},{"Nightvision Goggles"},{"Thermal Goggles"},{"Parachute"}, {"Fake Pistol"},{""}, {"Vehicle"}, {"Helicopter Blades"},
		{"Explosion"}, {""}, {"Drowned"}, {"Collision"}
};

new aVehicleNames[212][] =
{
        {"Landstalker"},    {"Bravura"},            {"Buffalo"},            {"Linerunner"},     {"Perrenial"},      {"Sentinel"},       {"Dumper"},
        {"Firetruck"},      {"Trashmaster"},        {"Stretch"},            {"Manana"},         {"Infernus"},       {"Voodoo"},         {"Pony"},           {"Mule"},
        {"Cheetah"},        {"Ambulance"},          {"Leviathan"},          {"Moonbeam"},       {"Esperanto"},      {"Taxi"},           {"Washington"},
        {"Bobcat"},         {"Mr Whoopee"},         {"BF Injection"},       {"Hunter"},         {"Premier"},        {"Enforcer"},       {"Securicar"},
        {"Banshee"},        {"Predator"},           {"Bus"},{"Rhino"},      {"Barracks"},       {"Hotknife"},       {"Artic Trailer 1"},      {"Previon"},
        {"Coach"},          {"Cabbie"},             {"Stallion"},           {"Rumpo"},          {"RC Bandit"},      {"Romero"},         {"Packer"},         {"Monster"},
        {"Admiral"},        {"Squalo"},             {"Seasparrow"},         {"Pizzaboy"},       {"Tram"},           {"Artic Trailer 2"},      {"Turismo"},
        {"Speeder"},        {"Reefer"},             {"Tropic"},             {"Flatbed"},        {"Yankee"},         {"Caddy"},          {"Solair"},         {"Berkley's RC Van"},
        {"Skimmer"},        {"PCJ-6_0_0"},          {"Faggio"},             {"Freeway"},        {"RC Baron"},       {"RC Raider"},      {"Glendale"},       {"Oceanic"},
        {"Sanchez"},        {"Sparrow"},            {"Patriot"},            {"Quad"},           {"Coastguard"},     {"Dinghy"},         {"Hermes"},         {"Sabre"},
        {"Rustler"},        {"ZR-3_5_0"},           {"Walton"},             {"Regina"},         {"Comet"},{"BMX"},  {"Burrito"},        {"Camper"},         {"Marquis"},
        {"Baggage"},        {"Dozer"},              {"Maverick"},           {"News Chopper"},   {"Rancher"},        {"FBI Rancher"},    {"Virgo"},          {"Greenwood"},
        {"Jetmax"},         {"Hotring"},            {"Sandking"},           {"Blista Compact"}, {"Police Maverick"},{"Boxville"},       {"Benson"},
        {"Mesa"},           {"RC Goblin"},          {"Hotring Racer A"},    {"Hotring Racer B"},{"Bloodring Banger"},{"Rancher"},
        {"Super GT"},       {"Elegant"},            {"Journey"},            {"Bike"},           {"Mountain Bike"},  {"Beagle"},         {"Cropdust"},       {"Stunt"},
        {"Tanker"},         {"Roadtrain"},          {"Nebula"},             {"Majestic"},       {"Buccaneer"},      {"Shamal"},         {"Hydra"},          {"FCR-900"},
        {"NRG-500"},        {"HPV1000"},            {"Cement Truck"},       {"Tow Truck"},      {"Fortune"},        {"Cadrona"},        {"FBI Truck"},
        {"Willard"},        {"Forklift"},           {"Tractor"},            {"Combine"},        {"Feltzer"},        {"Remington"},      {"Slamvan"},
        {"Blade"},          {"Freight"},            {"Streak"},             {"Vortex"},         {"Vincent"},        {"Bullet"},         {"Clover"},         {"Sadler"},
        {"Firetruck LA"},   {"Hustler"},            {"Intruder"},           {"Primo"},          {"Cargobob"},       {"Tampa"},          {"Sunrise"},        {"Merit"},
        {"Utility"},        {"Nevada"},             {"Yosemite"},           {"Windsor"},        {"Monster A"},      {"Monster B"},      {"Uranus"},         {"Jester"},
        {"Sultan"},         {"Stratum"},            {"Elegy"},              {"Raindance"},      {"RC Tiger"},       {"Flash"},          {"Tahoma"},         {"Savanna"},
        {"Bandito"},        {"Freight Flat"},       {"Streak Carriage"},    {"Kart"},           {"Mower"},          {"Duneride"},       {"Sweeper"},
        {"Broadway"},       {"Tornado"},            {"AT-400"},             {"DFT-30"},         {"Huntley"},        {"Stafford"},       {"BF-400"},         {"Newsvan"},
        {"Tug"},            {"Chemical Trailer"},          {"Emperor"},            {"Wayfarer"},       {"Euros"},          {"Hotdog"},         {"Club"},           {"Freight Carriage"},
        {"Artic Trailer 3"},      {"Andromada"},          {"Dodo"},               {"RC Cam"},         {"Launch"},         {"Police Car LSPD"},{"Police Car SFPD"},
        {"Police _LVPD"},   {"Police Ranger"},      {"Picador"},            {"SWAT. Van"},      {"Alpha"},          {"Phoenix"},        {"Glendale"},
        {"Sadler"},         {"Luggage Trailer A"},  {"Luggage Trailer B"},  {"Stair Trailer"},{"Boxville"},         {"Farm Plow"},
        {"Utility Trailer"}
};


//------------------------------------------------------------------------------
main(){} //---------------------------------------------------------------------
//------------------------------------------------------------------------------



public OnGameModeInit()
{
	UsePlayerPedAnims(); // Player movement
	AllowInteriorWeapons(1); // Allow weapons in interiors
	DisableInteriorEnterExits(); // Disables entering interiors (e.g. Burger shots)
	EnableStuntBonusForAll(0); // If you stunt you won't get any points (Value = 0)
	SetNameTagDrawDistance(20.0); // Distance to see other players name and Hp
	SetGravity(0.008); // Gravity
	GameType = 0;

	SetGameModeText("Attack-Defend"); // Text that appears on 'Mode' column when you click on a server in samp.exe
    SendRconCommand("mapname Lobby");

	LoadTextDraws(); // Loads all gloable textdraws
	LoadBases(); // Loads bases
	LoadDMs();

	if(!fexist(CONFIG_PATH)) dini_Create(CONFIG_PATH); // If config.ini don't exist in scriptfiles/attackdefend folder then it will create one.
	else LoadConfig();
    
	// Put the AddPlayerClass below 'LoadConfig' because we first need to tell the script the values of Skin[MAX_TEAMS] (e.g. Skin[ATTACKER]) and then use that value in AddPlayerClass.
	// If it was above 'LoadConfig' all the Skin variables (i.e. Skin[ATTACKER], Skin[DEFENDER], etc) would be 0, so every class (att, def, ref) would have CJ skin.

	AddPlayerClass(Skin[ATTACKER], 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); // attacker
    AddPlayerClass(Skin[DEFENDER], 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); // defender
    AddPlayerClass(Skin[REFEREE], 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); // referee

	SetWorldTime(MainTime); // Sets server time
	SetWeather(MainWeather); // Sets server weather

	TextColor[ATTACKER] = "{FF4444}";
	TextColor[DEFENDER] = "{3388FF}";
	TextColor[REFEREE] = "{FFFF88}";

	TDC[NON] = "~r~";
	TDC[ATTACKER] = "~r~";
    TDC[DEFENDER] = "~b~";
    TDC[REFEREE]= "~y~";

    TeamName[ATTACKER] = "Alpha";
    TeamName[DEFENDER] = "Beta";

	new iString[256];
	format(iString, sizeof(iString), "~l~~h~Rounds ~r~~h~%d~l~~h~/~r~~h~%d", CurrentRound, TotalRounds);
	TextDrawSetString(RoundsPlayed, iString);

	format(iString, sizeof(iString), "~r~~h~%s ~l~~h~(%d)  ~b~~h~%s ~l~~h~(%d)",TeamName[ATTACKER],TeamScore[ATTACKER],TeamName[DEFENDER],TeamScore[DEFENDER]);
    TextDrawSetString(TeamScoreText, iString);

//	iString = "~r~~h~Name\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tKills\t\t\t\tDeaths\t\t\t\tDamage\t\t\t\t\t\t\t~l~~h~Base\t\t\t\t\t\t\t~b~~h~Name\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tKills\t\t\t\tDeaths\t\t\t\tDamage";
	iString = "~r~~h~Name\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tKills\t\t\t\tDeaths\t\t\t\tDamage\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t~b~~h~Name\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tKills\t\t\t\tDeaths\t\t\t\tDamage";
	TextDrawSetString(EN_AttackerDefenderTitle, iString);
	

	
	SetTimer("OnScriptUpdate", 1000, true); // Timer that updates every second (will be using this for most stuff)

	return 1;
}



public OnGameModeExit()
{
	return 1;
}



public OnPlayerConnect(playerid)
{
	if(playerid > HighestID) HighestID = playerid;

	Player[playerid][Team] = NON;
    SetPlayerColor(playerid, 0xAAAAAAAA);
    
	SendClientMessage(playerid, -1, "{888888}~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
    SendClientMessage(playerid, -1, "{888888}Welcome To Attack and Defend Gamemode.");
    SendClientMessage(playerid, -1, "{888888}Use {FFFFFF}/help {888888}for all the public commands and etc.");
//    SendClientMessage(playerid, -1, "{888888}Search for {FFFFFF}'ddzproduction' {888888}on youtube -");
 //   SendClientMessage(playerid, -1, "{888888}for the tutorial on how this GM is being build.");
	SendClientMessage(playerid, -1, "{888888}~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
    
    GetPlayerName(playerid, Player[playerid][Name], 24); // Gets the name of every player that joins the server and saves it in 'Name' i.e. Player[playerid][Name]
	Player[playerid][NameWithoutTag] = RemoveClanTagFromName(playerid); // Removes clan tag from the player name and stores the new name in NameWithoutTag variable.

    new iString[160];
    format(iString, sizeof(iString), "{888888}Player {FFFFFF}%s {888888}connected to the server.", Player[playerid][Name]);
    SendClientMessageToAll(-1, iString);
    
	LoadPlayerTextDraws(playerid);

	// Reset all variables (So that the connected player don't have the same variable values as the player that left with the same playerid)

	Player[playerid][Level] = 0;
	Player[playerid][Weather] = MainWeather;
	Player[playerid][Time] = MainTime;
	Player[playerid][DMReadd] = 0;
	Player[playerid][RoundKills] = 0;
	Player[playerid][RoundDeaths] = 0;
	Player[playerid][RoundDamage] = 0;
	Player[playerid][WeaponPicked] = 0;
	Player[playerid][TotalKills] = 0;
	Player[playerid][TotalDeaths] = 0;
	Player[playerid][TotalDamage] = 0;
	Player[playerid][IsSpectatingID] = -1;

    Player[playerid][Logged] = false;
    Player[playerid][IgnoreSpawn] = false;
    Player[playerid][InDM] = false;
    Player[playerid][Syncing] = false;
    Player[playerid][Playing] = false;
    Player[playerid][WasInCP] = false;
    Player[playerid][IsKicked] = false;
	Player[playerid][Spectating] = false;
	Player[playerid][BeingSpeced] = false;
	Player[playerid][CalledByPlayer] = false;
	Player[playerid][WasInBase] = false;
	Player[playerid][TextDrawOnScreen] = false;
    
	return 1;
}

public OnPlayerRequestClass(playerid, classid)
{
	SetPlayerPos(playerid, 447.033, -4.735, 1000.734);
	SetPlayerFacingAngle(playerid, 178.626);
	SetPlayerInterior(playerid, 1);
	
	SetPlayerCameraPos(playerid, 446.918, -8.949, 1001.492);
	SetPlayerCameraLookAt(playerid, 447.033, -4.735, 1000.734);

	switch(classid) {
	    case 0: {
	        TextDrawShowForPlayer(playerid, AttackerText);
	        TextDrawHideForPlayer(playerid, DefenderText);
	        TextDrawHideForPlayer(playerid, RefereeText);
	        Player[playerid][Team] = ATTACKER;
		} case 1: {
	        TextDrawShowForPlayer(playerid, DefenderText);
	        TextDrawHideForPlayer(playerid, AttackerText);
	        TextDrawHideForPlayer(playerid, RefereeText);
	        Player[playerid][Team] = DEFENDER;
	    } case 2: {
	        TextDrawShowForPlayer(playerid, RefereeText);
	        TextDrawHideForPlayer(playerid, AttackerText);
	        TextDrawHideForPlayer(playerid, DefenderText);
	        Player[playerid][Team] = REFEREE;
		}
	}
	
	
	return 1;
}

public OnPlayerRequestSpawn(playerid)
{
    TextDrawHideForPlayer(playerid, AttackerText);
    TextDrawHideForPlayer(playerid, DefenderText);
    TextDrawHideForPlayer(playerid, RefereeText);

	switch(Player[playerid][Team]) {
	    case ATTACKER: SetPlayerColor(playerid, ATTACKER_NOT_PLAYING);
	    case DEFENDER: SetPlayerColor(playerid, DEFENDER_NOT_PLAYING);
	    case REFEREE: SetPlayerColor(playerid, REFEREE_COLOR);
	}
	
	new iString[180];
	format(iString, sizeof(iString), "~n~~n~~l~~h~Kills %s~h~%d~n~~l~~h~Damage %s~h~%.0f~n~~l~~h~Total Dmg %s~h~%.0f", TDC[Player[playerid][Team]], Player[playerid][RoundKills], TDC[Player[playerid][Team]], Player[playerid][RoundDamage], TDC[Player[playerid][Team]], Player[playerid][TotalDamage]);
	PlayerTextDrawSetString(playerid, RoundKillDmgTDmg[playerid], iString);

	PlayerTextDrawShow(playerid, FPSPingPacket[playerid]);
	PlayerTextDrawShow(playerid, RoundKillDmgTDmg[playerid]);
	for(new i = 0; i < 3; i++) {
		PlayerTextDrawShow(playerid, DoingDamage[i][playerid]);
		PlayerTextDrawShow(playerid, GettingDamaged[i][playerid]);
	}
//	PlayerTextDrawShow(playerid, RoundText[playerid]);
	if(Current != -1) TextDrawShowForPlayer(playerid, RoundStats);
	PlayerTextDrawShow(playerid, WhoSpec[0][playerid]);
	PlayerTextDrawShow(playerid, WhoSpec[1][playerid]);
	TextDrawShowForPlayer(playerid, RoundsPlayed);
	TextDrawShowForPlayer(playerid, TeamScoreText);
	TextDrawShowForPlayer(playerid, BaseID_VS);


 //  	PlayerTextDrawSetString(playerid, WhoSpec[0][playerid], pString);
//	printf(pString);

	return 1;
}


public OnPlayerSpawn(playerid)
{
	if(Player[playerid][IgnoreSpawn] == true) {
	    Player[playerid][IgnoreSpawn] = false;
	    return 0;
	}

	ClearAnimations(playerid);

	if(Player[playerid][DMReadd] > 0) {
	    SpawnInDM(playerid, Player[playerid][DMReadd]);
	    return 1;
	}


	SetPlayerPos(playerid, MainSpawn[0], MainSpawn[1], MainSpawn[2]);
	SetPlayerFacingAngle(playerid, MainSpawn[3]);
	SetCameraBehindPlayer(playerid);
	SetPlayerInterior(playerid, MainInterior); // Set player interior to 0 since the current lobby is an exterior (Exterior ID = 0)
	SetPlayerVirtualWorld(playerid, 0); // Set player virtual world to 0 so that if for example, the base is in lobby and the player died and spawned in lobby, he won't see the ones in the round because they will be in a different virtual world.
	
	SetPlayerHealth(playerid, 100);
	SetPlayerArmour(playerid, 100);
	
	ResetPlayerWeapons(playerid); // Reset player weapons when they spawn
	SetPlayerTeam(playerid, playerid); // Since playerid is different for every player (i.e. no two players have the same ID in the server) we can set the player team to the value of his ID so that he is able to shot everyone else. (Remember players in the same team can't shot each other.)

	ColorFix(playerid); // Fixes player color based on their team.

	if(Current != -1) LoadPlayerVariables(playerid);

	return 1;
}


public OnPlayerDisconnect(playerid, reason)
{
	if(Player[playerid][Spectating] == true && IsPlayerConnected(Player[playerid][IsSpectatingID])) StopSpectate(playerid);

   	if(playerid == HighestID) {
	    new highID = 0;
		for(new i = 0; i <= HighestID; i++) if(IsPlayerConnected(i) && i != playerid) {
    	    if(i > highID) {
    	        highID = i;
    	    }
		}
		HighestID = highID;
	}

	new iString[180];
    switch (reason){
		case 0:{
			if(Player[playerid][Playing] == false) {
				format(iString, sizeof(iString), "{888888}<< {FFFFFF}%s {888888}has left the server .:{FFFFFF}Timeout{888888}:.",Player[playerid][Name]);
			} else {
			    new Float:HP[2];
			    GetPlayerHealth(playerid, HP[0]);
			    GetPlayerArmour(playerid, HP[1]);
			    format(iString, sizeof(iString), "{888888}<< {FFFFFF}%s {888888}has left the server .:{FFFFFF}Timeout{888888}:. HP {FFFFFF}%.0f {888888}| Armour {FFFFFF} %.0f", Player[playerid][Name], HP[0], HP[1]);
			}
		} case 1: {
			if(Player[playerid][Playing] == false) {
				format(iString, sizeof(iString), "{888888}<< {FFFFFF}%s {888888}has left the server .:{FFFFFF}Leaving{888888}:.",Player[playerid][Name]);
			} else {
			    new Float:HP[2];
			    GetPlayerHealth(playerid, HP[0]);
			    GetPlayerArmour(playerid, HP[1]);
			    format(iString, sizeof(iString), "{888888}<< {FFFFFF}%s {888888}has left the server .:{FFFFFF}Leaving{888888}:. HP {FFFFFF}%.0f {888888}| Armour {FFFFFF} %.0f", Player[playerid][Name], HP[0], HP[1]);
			}
		} case 2: {
			if(Player[playerid][IsKicked] == true)format(iString, sizeof(iString), "{888888}<< {FFFFFF}%s {888888}has left the server .:{FFFFFF}Kicked{888888}:.",Player[playerid][Name]);
			else format(iString, sizeof(iString), "{888888}<< {FFFFFF}%s {888888}has left the server .:{FFFFFF}Banned{888888}:.",Player[playerid][Name]);
		}
	}
	SendClientMessageToAll(-1,iString);

	if(Player[playerid][WeaponPicked] > 0){
 		TimesPicked[Player[playerid][Team]][Player[playerid][WeaponPicked]-1]--;
 		Player[playerid][WeaponPicked] = 0;
	}

	if(Player[playerid][WasInCP] == true) {
	    PlayersInCP--;
		if(PlayersInCP <= 0) {
		    CurrentCPTime = ConfigCPTime;
		}
	}

    if(Player[playerid][Playing] == true) PlayersAlive[Player[playerid][Team]]--;

	if(Player[playerid][BeingSpeced] == true) {
		foreach(new i : Player) {
		    if(Player[i][Spectating] == true && Player[i][IsSpectatingID] == playerid) {
				if(Current != -1 && (Player[i][Team] == ATTACKER || Player[i][Team] == ATTACKER_SUB || Player[i][Team] == DEFENDER || Player[i][Team] == DEFENDER_SUB)) {
					SpectateNextTeamPlayer(i);
				} else {
				    SpectateNextPlayer(i);
				}
			}
		}
	}

	return 1;
}




public OnPlayerDeath(playerid, killerid, reason)
{
	new iString[180];

	new bool:TempPlaying;
	if(Player[playerid][Playing] == true) TempPlaying = true;
	else TempPlaying = false;

	if(killerid == INVALID_PLAYER_ID) {
	    if(Current == -1) SendDeathMessage(INVALID_PLAYER_ID, playerid, reason);
	    
	    if(TempPlaying == true) {
            SendDeathMessage(INVALID_PLAYER_ID, playerid, reason);
			Player[playerid][RoundDeaths]++;
			Player[playerid][TotalDeaths]++;
	    }

	} else if( killerid != INVALID_PLAYER_ID && IsPlayerConnected(killerid)) {

		if(Current == -1) SendDeathMessage(killerid, playerid, reason);

		if(Player[killerid][InDM] == true) {
			SetPlayerHealth(killerid, 100);
			SetPlayerArmour(killerid, 100);
		}
		
		if(TempPlaying == true) {
		    SendDeathMessage(killerid, playerid, reason);
		    Player[killerid][RoundKills]++;
		    Player[killerid][TotalKills]++;
		    Player[playerid][RoundDeaths]++;
		    Player[playerid][TotalDeaths]++;

			format(iString, sizeof(iString), "~n~~n~~l~~h~Kills %s~h~%d~n~~l~~h~Damage %s~h~%.0f~n~~l~~h~Total Dmg %s~h~%.0f", TDC[Player[killerid][Team]], Player[killerid][RoundKills], TDC[Player[killerid][Team]], Player[killerid][RoundDamage], TDC[Player[killerid][Team]], Player[killerid][TotalDamage]);
			PlayerTextDrawSetString(killerid, RoundKillDmgTDmg[killerid], iString);

		}
	}

	Player[playerid][InDM] = false;
	Player[playerid][Playing] = false;
	
	if(Player[playerid][WeaponPicked] > 0){
 		TimesPicked[Player[playerid][Team]][Player[playerid][WeaponPicked]-1]--;
 		Player[playerid][WeaponPicked] = 0;
	}

	if(TempPlaying == true) PlayersAlive[Player[playerid][Team]]--;

	if(Player[playerid][WasInCP] == true) {
	    PlayersInCP--;
	    Player[playerid][WasInCP] = false;
		if(PlayersInCP <= 0) {
		    CurrentCPTime = ConfigCPTime;
		}
	}

	if(Player[playerid][BeingSpeced] == true) {
		foreach(new i : Player) {
		    if(Player[i][Spectating] == true && Player[i][IsSpectatingID] == playerid) {
				if(Current != -1 && (Player[i][Team] == ATTACKER || Player[i][Team] == ATTACKER_SUB || Player[i][Team] == DEFENDER || Player[i][Team] == DEFENDER_SUB)) {
					SpectateNextTeamPlayer(i);
				} else {
				    SpectateNextPlayer(i);
				}
			}
		}
	}

	if(TempPlaying == true) {
	    if(Player[playerid][Team] == ATTACKER) {
	        foreach(new i : Player) {
	            if(Player[i][Team] == ATTACKER && Player[i][Playing] == true) {
					SpectatePlayer(playerid, i);
					break;
				}
			}
		} else if(Player[playerid][Team] == DEFENDER) {
		    foreach(new i : Player) {
		        if(Player[i][Team] == DEFENDER && Player[i][Playing] == true) {
		            SpectatePlayer(playerid, i);
					break;
				}
			}
		}
	}

	SetPlayerHealth(playerid, 100);
	SpawnPlayer(playerid);
	return 1;
}





public OnPlayerText(playerid, text[])
{
	if(text[0] == '!') {
	    new ChatColor;
	    switch(Player[playerid][Team]) {
	        case REFEREE: 		ChatColor = 0xFFFF90FF;
	        case DEFENDER: 		ChatColor = 0x0088FFFF;
	        case ATTACKER: 		ChatColor = 0xFF2040FF;
	        case ATTACKER_SUB: 	ChatColor = ATTACKER_SUB_COLOR;
	        case DEFENDER_SUB: 	ChatColor = DEFENDER_SUB_COLOR;
	        case NON: 			{ SendClientMessage(playerid, -1, "{CCFF99}>> {EEEEEE}Error: {CCFF99}You must be part of a team."); return 0; }
	    }
		format(ChatString,sizeof(ChatString),".: Team Chat | %s (%d) | %s", Player[playerid][Name], playerid, text[1]);

		foreach(new i : Player) {
			if(Player[i][Team] != NON) {
		        if((Player[playerid][Team] == ATTACKER || Player[playerid][Team] == ATTACKER_SUB) && (Player[i][Team] == ATTACKER || Player[i][Team] == ATTACKER_SUB)) { SendClientMessage(i, ChatColor, ChatString); PlayerPlaySound(i,1137,0.0,0.0,0.0); }
		        if((Player[playerid][Team] == DEFENDER || Player[playerid][Team] == DEFENDER_SUB) && (Player[i][Team] == DEFENDER || Player[i][Team] == DEFENDER_SUB)) { SendClientMessage(i, ChatColor, ChatString); PlayerPlaySound(i,1137,0.0,0.0,0.0); }
			}
	    }
	    return 0;
	}


	return 1;
}



public OnPlayerStateChange(playerid, newstate, oldstate)
{
    switch(newstate) {
	    case PLAYER_STATE_DRIVER: {
            if(Player[playerid][Team] == DEFENDER && Player[playerid][Playing] == true) {
				RemovePlayerFromVehicle(playerid);
				return 1;
			}

			SetPlayerArmedWeapon(playerid,0);

			if(Player[playerid][BeingSpeced] == true) {
	            foreach(new i : Player) {
		            if(Player[i][Spectating] == true && Player[i][IsSpectatingID] == playerid) {
			            TogglePlayerSpectating(i, 1);
			            PlayerSpectateVehicle(i, GetPlayerVehicleID(playerid));
		            }
		        }
			}
		} case PLAYER_STATE_PASSENGER: {
            if(Player[playerid][Team] == DEFENDER && Player[playerid][Playing] == true) {
				RemovePlayerFromVehicle(playerid);
				return 1;
			}

			SetPlayerArmedWeapon(playerid,0);

			if(Player[playerid][BeingSpeced] == true) {
	            foreach(new i : Player) {
		            if(Player[i][Spectating] == true && Player[i][IsSpectatingID] == playerid) {
			            TogglePlayerSpectating(i, 1);
			            PlayerSpectateVehicle(i, GetPlayerVehicleID(playerid));
		            }
		        }
			}
	    } case PLAYER_STATE_ONFOOT: {
	        if(oldstate == PLAYER_STATE_DRIVER || oldstate == PLAYER_STATE_PASSENGER) {
				if(Player[playerid][BeingSpeced] == true) {
		            foreach(new i : Player) {
			            if(Player[i][Spectating] == true && Player[i][IsSpectatingID] == playerid) {
				            TogglePlayerSpectating(i, 1);
				            PlayerSpectatePlayer(i, playerid);
			            }
			        }
				}
			}
	    }
    }

	return 1;
}

public OnPlayerInteriorChange(playerid, newinteriorid, oldinteriorid)
{
	foreach (new i : Player) {
	    if(Player[i][Spectating] == true && Player[i][IsSpectatingID] == playerid){
			SetPlayerInterior(i,newinteriorid);
		}
	}

	return 1;
}

public OnPlayerEnterCheckpoint(playerid)
{
    if(!IsPlayerInAnyVehicle(playerid) && Player[playerid][Playing] == true) {
		switch(Player[playerid][Team]) {
		    case ATTACKER: {
				PlayersInCP++;
				Player[playerid][WasInCP] = true;
				SetPlayerColor(playerid,0xFFFFFF55);
			} case DEFENDER: {
			    PlayersInCP = 0;
			    CurrentCPTime = ConfigCPTime;
			}
		}
	}

    return 1;
}

public OnPlayerLeaveCheckpoint(playerid)
{
	if(Player[playerid][Team] == ATTACKER && Player[playerid][WasInCP] == true) {
		PlayersInCP--;
	 	Player[playerid][WasInCP] = false;
	    ColorFix(playerid);
	    RadarFix();

		if(PlayersInCP <= 0) {
		    CurrentCPTime = ConfigCPTime;
		}
	}
    return 1;
}














public OnPlayerKeyStateChange(playerid, newkeys, oldkeys)
{
	if(newkeys == 160 && (GetPlayerWeapon(playerid) == 0 || GetPlayerWeapon(playerid) == 1) && !IsPlayerInAnyVehicle(playerid)){
		SyncPlayer(playerid);
		return 1;
	}

	if(Player[playerid][TextDrawOnScreen] == true && PRESSED(4)) {
	    HideEndRoundTextDraw(playerid);
	}
	
	if(IsPlayerInAnyVehicle(playerid)) {
	    if (PRESSED(KEY_FIRE) && GetPlayerState(playerid) == PLAYER_STATE_DRIVER ) {
	          AddVehicleComponent(GetPlayerVehicleID(playerid), 1010);
	    }
	    return 1;
	}

	if(Player[playerid][Spectating] == true) {
		if(newkeys == 4) {
            Player[playerid][CalledByPlayer] = true;

			if(Current != -1 && (Player[playerid][Team] == ATTACKER || Player[playerid][Team] == ATTACKER_SUB || Player[playerid][Team] == DEFENDER || Player[playerid][Team] == DEFENDER_SUB)) {
				SpectateNextTeamPlayer(playerid);
			} else {
			    SpectateNextPlayer(playerid);
			}
		} else if(newkeys == 128) {
            Player[playerid][CalledByPlayer] = true;

			if(Current != -1 && (Player[playerid][Team] == ATTACKER || Player[playerid][Team] == ATTACKER_SUB || Player[playerid][Team] == DEFENDER || Player[playerid][Team] == DEFENDER_SUB)) {
				SpectatePreviousTeamPlayer(playerid);
			} else {
			    SpectatePreviousPlayer(playerid);
			}
		}
	}

	if(Current == -1 && PRESSED(KEY_YES)) {
	    SelectTextDraw(playerid, 0xFF0000FF);
		return 1;
	}

	return 1;
}

public OnRconLoginAttempt(ip[], password[], success)
{
	return 1;
}

public OnPlayerUpdate(playerid)
{
	return 1;
}

public OnPlayerStreamIn(playerid, forplayerid)
{
	if(Player[playerid][Playing] == true && Player[forplayerid][Playing] == true){
		if(Player[forplayerid][Team] != Player[playerid][Team]){
			SetPlayerMarkerForPlayer(forplayerid,playerid,GetPlayerColor(playerid) & 0xFFFFFF00);
		} else {
			SetPlayerMarkerForPlayer(forplayerid,playerid,GetPlayerColor(playerid) | 0x00000055);
		}
	} else if(Player[playerid][Playing] == false && Player[forplayerid][Playing] == true) {
		if(Player[forplayerid][Team] != Player[playerid][Team]){
			SetPlayerMarkerForPlayer(forplayerid,playerid,GetPlayerColor(playerid) & 0xFFFFFF00);
		} else {
			SetPlayerMarkerForPlayer(forplayerid,playerid,GetPlayerColor(playerid) | 0x00000055);
		}
	}
	
	return 1;
}

public OnPlayerStreamOut(playerid, forplayerid)
{
	if(Player[playerid][Playing] == true && Player[forplayerid][Playing] == true){
		if(Player[forplayerid][Team] != Player[playerid][Team]){
			SetPlayerMarkerForPlayer(forplayerid,playerid,GetPlayerColor(playerid) & 0xFFFFFF00);
		} else {
			SetPlayerMarkerForPlayer(forplayerid,playerid,GetPlayerColor(playerid) | 0x00000055);
		}
	} else if(Player[playerid][Playing] == false && Player[forplayerid][Playing] == true) {
		if(Player[forplayerid][Team] != Player[playerid][Team]){
			SetPlayerMarkerForPlayer(forplayerid,playerid,GetPlayerColor(playerid) & 0xFFFFFF00);
		} else {
			SetPlayerMarkerForPlayer(forplayerid,playerid,GetPlayerColor(playerid) | 0x00000055);
		}
	}
	return 1;
}

public OnVehicleStreamIn(vehicleid, forplayerid)
{
	return 1;
}

public OnVehicleStreamOut(vehicleid, forplayerid)
{
	return 1;
}

public OnPlayerTakeDamage(playerid, issuerid, Float: amount, weaponid)
{
	PlayerPlaySound(playerid, 1131, 0, 0, 0);
	
	new Float:Health[3], Float:Damage;
	GetPlayerHealth(playerid, Health[0]);
	GetPlayerArmour(playerid, Health[1]);
	
	if(Health[0] > 0) {
	    if(amount > Health[0]) {
	        Damage = amount - Health[0];
	        amount = amount - Damage;
		}
	}
	
	Health[2] = (Health[0] + Health[1]) - amount;
	if(Health[2] < 0) Health[2] = 0;
	
	new iString[160];

	if(issuerid != INVALID_PLAYER_ID) {
		if(Player[issuerid][Playing] == true && (Player[issuerid][Team] == Player[playerid][Team])) return 1;
		if(Player[issuerid][Playing] == true && Player[playerid][Playing] == false) return 1;
		
		PlayerPlaySound(issuerid,17802,0.0,0.0,0.0);

		if(Player[issuerid][Playing] == true || Player[playerid][Playing] == true) {
			Player[issuerid][RoundDamage] += amount;
			Player[issuerid][TotalDamage] += amount;
			format(iString, sizeof(iString), "~n~~n~~l~~h~Kills %s~h~%d~n~~l~~h~Damage %s~h~%.0f~n~~l~~h~Total Dmg %s~h~%.0f", TDC[Player[issuerid][Team]], Player[issuerid][RoundKills], TDC[Player[issuerid][Team]], Player[issuerid][RoundDamage], TDC[Player[issuerid][Team]], Player[issuerid][TotalDamage]);
			PlayerTextDrawSetString(issuerid, RoundKillDmgTDmg[issuerid], iString);

			TeamHP[Player[playerid][Team]] = TeamHP[Player[playerid][Team]] - amount;
		}


		HPLost[0][issuerid][playerid] += amount;
		HPLost[1][playerid][issuerid] += amount;
		
		if(Declared[0][issuerid] == false && gLastHit[1][issuerid] != playerid && gLastHit[2][issuerid] != playerid){
		    gLastHit[0][issuerid] = playerid;
			Declared[0][issuerid] = true;
		}

		if(gLastHit[0][issuerid] == playerid) {
  			format(iString, sizeof(iString), "%s%s	~l~~h~/ -%.0f %s%s ~l~~h~- %.0f", TDC[Player[playerid][Team]], Player[playerid][NameWithoutTag], HPLost[0][issuerid][playerid], TDC[Player[playerid][Team]], WeaponNames[weaponid], Health[2]);
	        PlayerTextDrawSetString(issuerid, DoingDamage[0][issuerid], iString);
			TakeDmgCD[0][issuerid] = 1;
			H[0][issuerid] = playerid;

			if(Player[issuerid][BeingSpeced] == true) {
				foreach(new i : Player) {
			        if(Player[i][Spectating] == true && Player[i][IsSpectatingID] == issuerid) {
  						format(iString, sizeof(iString), "%s%s	~l~~h~/ -%.0f %s%s ~l~~h~- %.0f", TDC[Player[playerid][Team]], Player[playerid][NameWithoutTag], HPLost[0][issuerid][playerid], TDC[Player[playerid][Team]], WeaponNames[weaponid], Health[2]);
				        PlayerTextDrawSetString(i, DoingDamage[0][issuerid], iString);
				        PlayerPlaySound(i, 17802,0.0,0.0,0.0);
						TakeDmgCD[0][i] = 1;
						H[0][i] = i;
					}
				}
			}
		} else {
			if(Declared[1][issuerid] == false && gLastHit[2][issuerid] != playerid){
			    gLastHit[1][issuerid] = playerid;
				Declared[1][issuerid] = true;
			}

			if(gLastHit[1][issuerid] == playerid )
			{
	            format(iString, sizeof(iString), "%s%s	~l~~h~/ -%.0f %s%s ~l~~h~- %.0f", TDC[Player[playerid][Team]], Player[playerid][NameWithoutTag], HPLost[0][issuerid][playerid], TDC[Player[playerid][Team]], WeaponNames[weaponid], Health[2]);
	            PlayerTextDrawSetString(issuerid, DoingDamage[1][issuerid], iString);
				TakeDmgCD[1][issuerid] = 1;
                H[1][issuerid] = playerid;

				if(Player[issuerid][BeingSpeced] == true) {
				    foreach(new i : Player){
				        if(Player[i][Spectating] == true && Player[i][IsSpectatingID] == issuerid) {
							format(iString, sizeof(iString), "%s%s	~l~~h~/ -%.0f %s%s ~l~~h~- %.0f", TDC[Player[playerid][Team]], Player[playerid][NameWithoutTag], HPLost[0][issuerid][playerid], TDC[Player[playerid][Team]], WeaponNames[weaponid], Health[2]);				            PlayerTextDrawSetString(i, DoingDamage[1][issuerid], iString);
					        PlayerPlaySound(i, 17802,0.0,0.0,0.0);
							TakeDmgCD[1][i] = 1;
							H[1][i] = i;
						}
					}
				}
			} else {
   				gLastHit[2][issuerid] = playerid;
	            format(iString, sizeof(iString), "%s%s	~l~~h~/ -%.0f %s%s ~l~~h~- %.0f", TDC[Player[playerid][Team]], Player[playerid][NameWithoutTag], HPLost[0][issuerid][playerid], TDC[Player[playerid][Team]], WeaponNames[weaponid], Health[2]);
				PlayerTextDrawSetString(issuerid, DoingDamage[2][issuerid], iString);
				TakeDmgCD[2][issuerid] = 1;
                H[2][issuerid] = playerid;

				if(Player[issuerid][BeingSpeced] == true) {
				    foreach(new i : Player) {
				        if(Player[i][Spectating] == true && Player[i][IsSpectatingID] == issuerid) {
				            format(iString, sizeof(iString), "%s%s	~l~~h~/ -%.0f %s%s ~l~~h~- %.0f", TDC[Player[playerid][Team]], Player[playerid][NameWithoutTag], HPLost[0][issuerid][playerid], TDC[Player[playerid][Team]], WeaponNames[weaponid], Health[2]);
							PlayerTextDrawSetString(i, DoingDamage[2][issuerid], iString);
					        PlayerPlaySound(i,17802,0.0,0.0,0.0);
							TakeDmgCD[2][i] = 1;
							H[2][i] = i;
						}
					}
				}

			}
		}


		if(Declared[2][playerid] == false && gLastHit[4][playerid] != issuerid && gLastHit[5][playerid] != issuerid){
		    gLastHit[3][playerid] = issuerid;
			Declared[2][playerid] = true;
		}
		if(gLastHit[3][playerid] == issuerid) {
			format(iString, sizeof(iString), "%s%s	~l~~h~/ -%.0f %s%s ~l~~h~- %.0f", TDC[Player[playerid][Team]], Player[issuerid][NameWithoutTag], HPLost[1][playerid][issuerid], TDC[Player[playerid][Team]], WeaponNames[weaponid], Health[2]);
        	PlayerTextDrawSetString(playerid, GettingDamaged[0][playerid], iString);
			TakeDmgCD[3][playerid] = 1;
			H[3][playerid] = issuerid;

			if(Player[playerid][BeingSpeced] == true) {
			    foreach(new i : Player) {
			        if(Player[i][Spectating] == true && Player[i][IsSpectatingID] == playerid) {
						format(iString, sizeof(iString), "%s%s	~l~~h~/ -%.0f %s%s ~l~~h~- %.0f", TDC[Player[playerid][Team]], Player[issuerid][NameWithoutTag], HPLost[1][playerid][issuerid], TDC[Player[playerid][Team]], WeaponNames[weaponid], Health[2]);
			        	PlayerTextDrawSetString(i, GettingDamaged[0][playerid], iString);
				        PlayerPlaySound(i,1131,0.0,0.0,0.0);
						TakeDmgCD[3][i] = 1;
						H[3][i] = i;
					}
				}
			}
		} else {
			if(Declared[3][playerid] == false && gLastHit[5][playerid] != issuerid) {
			    gLastHit[4][playerid] = issuerid;
				Declared[3][playerid] = true;
			}
			if(gLastHit[4][playerid] == issuerid) {
				format(iString, sizeof(iString), "%s%s	~l~~h~/ -%.0f %s%s ~l~~h~- %.0f", TDC[Player[playerid][Team]], Player[issuerid][NameWithoutTag], HPLost[1][playerid][issuerid], TDC[Player[playerid][Team]], WeaponNames[weaponid], Health[2]);
	        	PlayerTextDrawSetString(playerid, GettingDamaged[1][playerid], iString);
				TakeDmgCD[4][playerid] = 1;
				H[4][playerid] = issuerid;

				if(Player[playerid][BeingSpeced] == true) {
				    foreach(new i : Player) {
				        if(Player[i][Spectating] == true && Player[i][IsSpectatingID] == playerid) {
							format(iString, sizeof(iString), "%s%s	~l~~h~/ -%.0f %s%s ~l~~h~- %.0f", TDC[Player[playerid][Team]], Player[issuerid][NameWithoutTag], HPLost[1][playerid][issuerid], TDC[Player[playerid][Team]], WeaponNames[weaponid], Health[2]);
				        	PlayerTextDrawSetString(i, GettingDamaged[1][playerid], iString);
					        PlayerPlaySound(i,1131,0.0,0.0,0.0);
							TakeDmgCD[4][i] = 1;
							H[4][i] = i;
						}
					}
				}
			} else {
			    gLastHit[5][playerid] = issuerid;
				format(iString, sizeof(iString), "%s%s	~l~~h~/ -%.0f %s%s ~l~~h~- %.0f", TDC[Player[playerid][Team]], Player[issuerid][NameWithoutTag], HPLost[1][playerid][issuerid], TDC[Player[playerid][Team]], WeaponNames[weaponid], Health[2]);
	        	PlayerTextDrawSetString(playerid, GettingDamaged[2][playerid], iString);
				TakeDmgCD[5][playerid] = 1;
				H[5][playerid] = issuerid;

				if(Player[playerid][BeingSpeced] == true) {
				    foreach(new i : Player) {
				        if(Player[i][Spectating] == true && Player[i][IsSpectatingID] == playerid) {
							format(iString, sizeof(iString), "%s%s	~l~~h~/ -%.0f %s%s ~l~~h~- %.0f", TDC[Player[playerid][Team]], Player[issuerid][NameWithoutTag], HPLost[1][playerid][issuerid], TDC[Player[playerid][Team]], WeaponNames[weaponid], Health[2]);
				        	PlayerTextDrawSetString(i, GettingDamaged[2][playerid], iString);
					        PlayerPlaySound(i,1131,0.0,0.0,0.0);
							TakeDmgCD[5][i] = 1;
							H[5][i] = i;
						}
					}
				}
			}
		}
	} else {
		if(GetPlayerState(playerid) != PLAYER_STATE_WASTED) {
			ILost[playerid] += amount;
			if(gLastHit[3][playerid] < 0) {
				format(iString, sizeof(iString), "~l~~h~-%.0f %s%s ~l~~h~- %.0f", ILost[playerid], TDC[Player[playerid][Team]], WeaponNames[weaponid], Health[2]);
	        	PlayerTextDrawSetString(playerid, GettingDamaged[0][playerid], iString);
				TakeDmgCD[6][playerid] = 1;

				if(Player[playerid][BeingSpeced] == true  ) {
				    foreach(new i : Player) {
				        if(Player[i][Spectating] == true && Player[i][IsSpectatingID] == playerid) {
							format(iString, sizeof(iString), "~l~-%.0f %s~h~%s ~l~~h~- %.0f", ILost[playerid], TDC[Player[playerid][Team]], WeaponNames[weaponid], Health[2]);
				        	PlayerTextDrawSetString(i, GettingDamaged[0][playerid], iString);
					        PlayerPlaySound(i,1131,0.0,0.0,0.0);
							TakeDmgCD[6][i] = 1;
						}
					}
				}

			} else {
				if(gLastHit[4][playerid] < 0) {
					format(iString, sizeof(iString), "~l~~h~-%.0f %s%s ~l~~h~- %.0f", ILost[playerid], TDC[Player[playerid][Team]], WeaponNames[weaponid], Health[2]);
		        	PlayerTextDrawSetString(playerid, GettingDamaged[1][playerid], iString);
					TakeDmgCD[7][playerid] = 1;

					if(Player[playerid][BeingSpeced] == true ) {
					    foreach(new i : Player) {
					        if(Player[i][Spectating] == true && Player[i][IsSpectatingID] == playerid) {
								format(iString, sizeof(iString), "~l~-%.0f %s~h~%s ~l~~h~- %.0f", ILost[playerid], TDC[Player[playerid][Team]], WeaponNames[weaponid], Health[2]);
					        	PlayerTextDrawSetString(i, GettingDamaged[1][playerid], iString);
						        PlayerPlaySound(i,1131,0.0,0.0,0.0);
								TakeDmgCD[7][i] = 1;
							}
						}
					}

				} else {
					format(iString, sizeof(iString), "~l~~h~-%.0f %s%s ~l~~h~- %.0f", ILost[playerid], TDC[Player[playerid][Team]], WeaponNames[weaponid], Health[2]);
		        	PlayerTextDrawSetString(playerid, GettingDamaged[2][playerid], iString);
					TakeDmgCD[8][playerid] = 1;

					if(Player[playerid][BeingSpeced] == true ) {
					    foreach(new i : Player){
					        if(Player[i][Spectating] == true && Player[i][IsSpectatingID] == playerid){
        						format(iString, sizeof(iString), "~l~-%.0f %s~h~%s ~l~~h~- %.0f", ILost[playerid], TDC[Player[playerid][Team]], WeaponNames[weaponid], Health[2]);
					        	PlayerTextDrawSetString(i, GettingDamaged[2][playerid], iString);
						        PlayerPlaySound(i,1131,0.0,0.0,0.0);
								TakeDmgCD[8][i] = 1;
							}
						}
					}

				}
			}
		}
	}


	return 1;
}




public OnDialogResponse(playerid, dialogid, response, listitem, inputtext[])
{
	new iString[160];

	if(dialogid == DIALOG_WEAPONS_TYPE) {
		if(response == 1) {
			if(listitem != 0) {
				if((Player[playerid][Team] == ATTACKER && TimesPicked[ATTACKER][listitem-1] >= WeaponLimit[listitem-1]) || (Player[playerid][Team] == DEFENDER && TimesPicked[DEFENDER][listitem-1] >= WeaponLimit[listitem-1])) {
	                ShowPlayerWeaponMenu(playerid, Player[playerid][Team]);
	                SendClientMessage(playerid, -1, "{888888}>> {EEEEEE}Error: {888888}This Weapon Set Is Currently Full.");
					return 1;
		        }
			}
			
			switch(listitem) {
			    case 0: {
					ShowPlayerWeaponMenu(playerid, Player[playerid][Team]);
					return 1;
	            } case 1: { // M4 and MP5
	                GivePlayerWeapon(playerid, M4, 9999);
	                GivePlayerWeapon(playerid, MP5, 9999);
	                TimesPicked[Player[playerid][Team]][listitem-1]++;
	                Player[playerid][WeaponPicked] = listitem;
					format(iString, sizeof(iString), "{FFFFFF}%s{888888} has selected ({FFFFFF}M4{888888} and {FFFFFF}MP5{888888}).", Player[playerid][Name]);
				} case 2: { // M4 and Shotgun
	                GivePlayerWeapon(playerid, SHOTGUN, 9999);
	                GivePlayerWeapon(playerid, M4, 9999);
	                TimesPicked[Player[playerid][Team]][listitem-1]++;
	                Player[playerid][WeaponPicked] = listitem;
					format(iString, sizeof(iString), "{FFFFFF}%s{888888} has selected ({FFFFFF}M4{888888} and {FFFFFF}Shotgun{888888}).",Player[playerid][Name]);
				} case 3: { // Sniper and Shotgun
	                GivePlayerWeapon(playerid, SNIPER, 9999);
	                GivePlayerWeapon(playerid, SHOTGUN, 9999);
	                TimesPicked[Player[playerid][Team]][listitem-1]++;
	                Player[playerid][WeaponPicked] = listitem;
					format(iString, sizeof(iString), "{FFFFFF}%s{888888} has selected ({FFFFFF}Sniper{888888} and {FFFFFF}Shotgun{888888}).",Player[playerid][Name]);
				} case 4: { // Rifle and Shotgun
	                GivePlayerWeapon(playerid, RIFLE, 9999);
	                GivePlayerWeapon(playerid, SHOTGUN, 9999);
	                TimesPicked[Player[playerid][Team]][listitem-1]++;
	                Player[playerid][WeaponPicked] = listitem;
					format(iString, sizeof(iString), "{FFFFFF}%s{888888} has selected ({FFFFFF}Rifle{888888} and {FFFFFF}Shotgun{888888}).",Player[playerid][Name]);
				} case 5: { // Deagle and MP5
	                GivePlayerWeapon(playerid, DEAGLE, 9999);
	                GivePlayerWeapon(playerid, MP5, 9999);
	                TimesPicked[Player[playerid][Team]][listitem-1]++;
	                Player[playerid][WeaponPicked] = listitem;
					format(iString, sizeof(iString), "{FFFFFF}%s{888888} has selected ({FFFFFF}Deagle{888888} and {FFFFFF}MP5{888888}).",Player[playerid][Name]);
				} case 6: { // Deagle and AK-47
	                GivePlayerWeapon(playerid, DEAGLE, 9999);
	                GivePlayerWeapon(playerid, AK47, 9999);
	                TimesPicked[Player[playerid][Team]][listitem-1]++;
	                Player[playerid][WeaponPicked] = listitem;
					format(iString, sizeof(iString), "{FFFFFF}%s{888888} has selected ({FFFFFF}Deagle{888888} and {FFFFFF}AK-47{888888}).",Player[playerid][Name]);
				} case 7: { // Deagle and Shotgun
	                GivePlayerWeapon(playerid, DEAGLE, 9999);
	                GivePlayerWeapon(playerid, SHOTGUN, 9999);
	                TimesPicked[Player[playerid][Team]][listitem-1]++;
	                Player[playerid][WeaponPicked] = listitem;
					format(iString, sizeof(iString), "{FFFFFF}%s{888888} has selected ({FFFFFF}Deagle{888888} and {FFFFFF}Shotgun{888888}).",Player[playerid][Name]);
				} case 8: { // Deagle and Rifle
	                GivePlayerWeapon(playerid, DEAGLE, 9999);
	                GivePlayerWeapon(playerid, RIFLE, 9999);
	                TimesPicked[Player[playerid][Team]][listitem-1]++;
	                Player[playerid][WeaponPicked] = listitem;
					format(iString, sizeof(iString), "{FFFFFF}%s{888888} has selected ({FFFFFF}Deagle{888888} and {FFFFFF}Rifle{888888}).",Player[playerid][Name]);
				} case 9: { // Spas and Rifle
	                GivePlayerWeapon(playerid, COMBAT, 9999);
	                GivePlayerWeapon(playerid, RIFLE, 9999);
	                TimesPicked[Player[playerid][Team]][listitem-1]++;
	                Player[playerid][WeaponPicked] = listitem;
					format(iString, sizeof(iString), "{FFFFFF}%s{888888} has selected ({FFFFFF}Spas-12{888888} and {FFFFFF}Rifle{888888}).",Player[playerid][Name]);
				} case 10: { // Spas and Silencer
	                GivePlayerWeapon(playerid, SILENCER, 9999);
	                GivePlayerWeapon(playerid, COMBAT, 9999);
	                TimesPicked[Player[playerid][Team]][listitem-1]++;
	                Player[playerid][WeaponPicked] = listitem;
					format(iString, sizeof(iString), "{FFFFFF}%s{888888} has selected ({FFFFFF}Spas-12{888888} and {FFFFFF}Silencer{888888}).",Player[playerid][Name]);
				}
			}

	        switch(Player[playerid][Team]) {
				case ATTACKER: {
					foreach(new i : Player) {
                		if(Player[i][Team] == ATTACKER) SendClientMessage(i, -1, iString);
					}
				} case DEFENDER: {
				    foreach(new i : Player) {
                		if(Player[i][Team] == DEFENDER) SendClientMessage(i, -1, iString);
					}
				}
            }
		}
		return 1;
	}

	if(dialogid == DIALOG_CURRENT_TOTAL) {
		if(isnull(inputtext)) return 1;
        if(!IsNumeric(inputtext)) {
            SendClientMessage(playerid,-1,"{888888}>> {FFFFFF}Error: {888888}You can only use numeric input.");
			iString = "{888888}Enter current round or total rounds to be played:";
    		ShowPlayerDialog(playerid, DIALOG_CURRENT_TOTAL, DIALOG_STYLE_INPUT,"{888888}Rounds Dialog",iString,"Current","Total");
			return 1;
		}

		new Value = strval(inputtext);

	    if(response) {
	        CurrentRound = Value;
		} else {
		    TotalRounds = Value;
		}

		format(iString, sizeof(iString), "~l~~h~Rounds ~r~~h~%d~l~~h~/~r~~h~%d", CurrentRound, TotalRounds);
		TextDrawSetString(RoundsPlayed, iString);

		return 1;
	}
	        
	if(dialogid == DIALOG_TEAM_SCORE) {
		if(response) {
		    switch(listitem) {
		        case 0: {
					iString = "{888888}Enter {FF3333}Attacker {888888}Team Name Below:";
				    ShowPlayerDialog(playerid, DIALOG_ATT_NAME, DIALOG_STYLE_INPUT,"{888888}Attacker Team Name",iString,"Next","Close");
				} case 1: {
					format(iString, sizeof(iString), "{888888}Enter {FF3333}%s {888888}Team Score Below:", TeamName[ATTACKER]);
				    ShowPlayerDialog(playerid, DIALOG_ATT_SCORE, DIALOG_STYLE_INPUT,"{888888}Attacker Team Score",iString,"Next","Close");
				} case 2: {
				    TeamScore[ATTACKER] = 0;
				    TeamScore[DEFENDER] = 0;
				    CurrentRound = 0;

//                    BasesPlayed = " ";

					format(iString, sizeof(iString), "~r~~h~%s ~l~~h~(%d)  ~b~~h~%s ~l~~h~(%d)",TeamName[ATTACKER],TeamScore[ATTACKER],TeamName[DEFENDER],TeamScore[DEFENDER]);
				    TextDrawSetString(TeamScoreText, iString);
				    
					format(iString, sizeof(iString), "~l~~h~Rounds ~r~~h~%d~l~~h~/~r~~h~%d", CurrentRound, TotalRounds);
					TextDrawSetString(RoundsPlayed, iString);
				}
			}
		}
		return 1;
	}

	if(dialogid == DIALOG_ATT_NAME) {
	    if(response) {
			if(isnull(inputtext)) return 1;
			if(strlen(inputtext) > 6) {
            	SendClientMessage(playerid,-1,"{888888}>> {FFFFFF}Error: {888888}Team name is too long.");
				iString = "{888888}Enter {FF3333}Attacker {888888}Team Name Below:";
			    ShowPlayerDialog(playerid, DIALOG_ATT_NAME, DIALOG_STYLE_INPUT,"{888888}Attacker Team Name",iString,"Next","Close");
				return 1;
			}
			format(TeamName[ATTACKER], 24, inputtext);
			format(iString, sizeof(iString), "%s", TeamName[ATTACKER]);
			TextDrawSetString(AttackerText, iString);
			
			format(iString, sizeof(iString), "~r~~h~%s ~l~~h~(%d)  ~b~~h~%s ~l~~h~(%d)",TeamName[ATTACKER],TeamScore[ATTACKER],TeamName[DEFENDER],TeamScore[DEFENDER]);
		    TextDrawSetString(TeamScoreText, iString);
			
			iString = "{888888}Enter {FF3333}Defender {888888}Team Name Below:";
		    ShowPlayerDialog(playerid, DIALOG_DEF_NAME, DIALOG_STYLE_INPUT,"{888888}Defender Team Name",iString,"Ok","Close");
		}
		return 1;
	}
	
	if(dialogid == DIALOG_DEF_NAME) {
	    if(response) {
	        if(isnull(inputtext)) return 1;
	        if(strlen(inputtext) > 6) {
	           	SendClientMessage(playerid,-1,"{888888}>> {FFFFFF}Error: {888888}Team name is too long.");
				iString = "{888888}Enter {FF3333}Defender {888888}Team Name Below:";
			    ShowPlayerDialog(playerid, DIALOG_DEF_NAME, DIALOG_STYLE_INPUT,"{888888}Defender Team Name",iString,"Ok","Close");
				return 1;
			}
			format(TeamName[DEFENDER], 24, inputtext);
			format(iString, sizeof(iString), "%s", TeamName[DEFENDER]);
			TextDrawSetString(DefenderText, iString);
			
			format(iString, sizeof(iString), "~r~~h~%s ~l~~h~(%d)  ~b~~h~%s ~l~~h~(%d)",TeamName[ATTACKER],TeamScore[ATTACKER],TeamName[DEFENDER],TeamScore[DEFENDER]);
		    TextDrawSetString(TeamScoreText, iString);
		}
		return 1;
	}
	
	if(dialogid == DIALOG_ATT_SCORE) {
	    if(response) {
	        if(isnull(inputtext)) return 1;
	        if(!IsNumeric(inputtext)) {
	            SendClientMessage(playerid,-1,"{888888}>> {FFFFFF}Error: {888888}Score can only be numerical.");
				format(iString, sizeof(iString), "{888888}Enter {FF3333}%s {888888}Team Score Below:", TeamName[ATTACKER]);
			    ShowPlayerDialog(playerid, DIALOG_ATT_SCORE, DIALOG_STYLE_INPUT,"{888888}Attacker Team Score",iString,"Next","Close");
				return 1;
			}
			new Score = strval(inputtext);
			CurrentRound = Score + TeamScore[DEFENDER];

			if(CurrentRound >= TotalRounds) {
				SendClientMessage(playerid,-1,"{888888}>> {FFFFFF}Error: {888888}Attacker plus defender score is bigger than or equal to total rounds.");
				format(iString, sizeof(iString), "{888888}Enter {FF3333}%s {888888}Team Score Below:", TeamName[ATTACKER]);
			    ShowPlayerDialog(playerid, DIALOG_ATT_SCORE, DIALOG_STYLE_INPUT,"{888888}Attacker Team Score",iString,"Next","Close");
				return 1;
			}
			
			TeamScore[ATTACKER] = Score;
			
			format(iString, sizeof(iString), "~r~~h~%s ~l~~h~(%d)  ~b~~h~%s ~l~~h~(%d)",TeamName[ATTACKER],TeamScore[ATTACKER],TeamName[DEFENDER],TeamScore[DEFENDER]);
		    TextDrawSetString(TeamScoreText, iString);
		    
			format(iString, sizeof(iString), "~l~~h~Rounds ~r~~h~%d~l~~h~/~r~~h~%d", CurrentRound, TotalRounds);
			TextDrawSetString(RoundsPlayed, iString);
		    
			format(iString, sizeof(iString), "{888888}Enter {FF3333}%s {888888}Team Score Below:", TeamName[DEFENDER]);
		    ShowPlayerDialog(playerid, DIALOG_DEF_SCORE, DIALOG_STYLE_INPUT,"{888888}Defender Team Score",iString,"Ok","Close");
		}
		return 1;
	}

	if(dialogid == DIALOG_DEF_SCORE) {
	    if(response) {
	        if(isnull(inputtext)) return 1;
	        if(!IsNumeric(inputtext)) {
	            SendClientMessage(playerid,-1,"{888888}>> {FFFFFF}Error: {888888}Score can only be numerical.");
				format(iString, sizeof(iString), "{888888}Enter {FF3333}%s {888888}Team Score Below:", TeamName[DEFENDER]);
			    ShowPlayerDialog(playerid, DIALOG_DEF_SCORE, DIALOG_STYLE_INPUT,"{888888}Defender Team Score",iString,"Ok","Close");
				return 1;
			}

			new Score = strval(inputtext);
			CurrentRound = TeamScore[ATTACKER] + Score;

			if(CurrentRound >= TotalRounds) {
	            SendClientMessage(playerid,-1,"{888888}>> {FFFFFF}Error: {888888}Attacker plus defender score is bigger than or equal to total rounds.");
				format(iString, sizeof(iString), "{888888}Enter {FF3333}%s {888888}Team Score Below:", TeamName[DEFENDER]);
			    ShowPlayerDialog(playerid, DIALOG_DEF_SCORE, DIALOG_STYLE_INPUT,"{888888}Defender Team Score",iString,"Ok","Close");
				return 1;
			}
			TeamScore[DEFENDER] = Score;
			
			format(iString, sizeof(iString), "~r~~h~%s ~l~~h~(%d)  ~b~~h~%s ~l~~h~(%d)",TeamName[ATTACKER],TeamScore[ATTACKER],TeamName[DEFENDER],TeamScore[DEFENDER]);
		    TextDrawSetString(TeamScoreText, iString);

			format(iString, sizeof(iString), "~l~~h~Rounds ~r~~h~%d~l~~h~/~r~~h~%d", CurrentRound, TotalRounds);
			TextDrawSetString(RoundsPlayed, iString);
		}
		return 1;
	}
			
	return 1;
}

public OnPlayerClickPlayer(playerid, clickedplayerid, source)
{
	return 1;
}

public OnPlayerClickTextDraw(playerid, Text:clickedid)
{
	new iString[140];
	if(clickedid == RoundsPlayed) {
		iString = "{888888}Enter current round or total rounds to be played:";
	    ShowPlayerDialog(playerid, DIALOG_CURRENT_TOTAL, DIALOG_STYLE_INPUT,"{888888}Rounds Dialog",iString,"Current","Total");
	    return 1;
	}
	
	if(clickedid == TeamScoreText) {
	    iString = "{888888}Team Names\n{888888}Team Scores\n{888888}Reset Scores";
	    ShowPlayerDialog(playerid, DIALOG_TEAM_SCORE, DIALOG_STYLE_LIST,"{888888}Team Dialog",iString,"Select","Close");
		return 1;
	}
	
	
	return 0;
}


//------------------------------------------------------------------------------
// Commands
//------------------------------------------------------------------------------


public OnPlayerCommandReceived(playerid, cmdtext[])
{
	if(Player[playerid][Team] == NON) {
	    SendClientMessage(playerid, -1, "{888888}>> {EEEEEE}Error: {888888}You Need To Spawn To Be Able To Use Commands.");
		return 0;
	}
	
	return 1;
}

public OnPlayerCommandPerformed(playerid, cmdtext[], success)
{
	if(success == 0) { // If the command does not exist
		new str[140];
	    format(str, sizeof(str), "{888888}>> {FFFFFF}Error: {888888}Command \"{FFFFFF}%s\" {888888}is unknown.", cmdtext);
		SendClientMessage(playerid, -1, str);
	}

	return 1;
}

CMD:showagain(playerid, params[])
{
    ShowEndRoundTextDraw(playerid);
    return 1;
}

CMD:match(playerid, params[])
{
	SelectTextDraw(playerid, 0xFF0000FF);
	return 1;
}

CMD:select(playerid, params[])
{
	cmd_match(playerid, params);
	return 1;
}

CMD:goto(playerid,params[])
{
	if(isnull(params)) return SendClientMessage(playerid,-1,"{888888}>> {FFFFFF}USAGE: {888888}goto [Player ID]");
	new gid = strval(params);

	if(Player[playerid][Level] < 1 && !IsPlayerAdmin(playerid)) return SendClientMessage(playerid,-1,"{888888}>> {FFFFFF}Error: {888888}You Need To Be An Admin.");
	if(!IsPlayerConnected(gid) || gid == INVALID_PLAYER_ID) return SendClientMessage(playerid,-1,"{888888}>> {FFFFFF}Error: {888888}Player isn't connected.");
	if(gid == playerid) return SendClientMessage(playerid,-1,"{888888}>> {FFFFFF}Error: {888888}Can't go to yourself.");
	new Float:x, Float:y, Float:z;
	GetPlayerPos(gid,x,y,z);
	SetPlayerInterior(playerid,GetPlayerInterior(gid));
	SetPlayerVirtualWorld(playerid,GetPlayerVirtualWorld(gid));
	if(GetPlayerState(playerid) == PLAYER_STATE_DRIVER)
	{
	    SetVehiclePos(GetPlayerVehicleID(playerid),x+2,y,z);
		LinkVehicleToInterior(GetPlayerVehicleID(playerid),GetPlayerInterior(gid));
	    SetVehicleVirtualWorld(GetPlayerVehicleID(playerid),GetPlayerVirtualWorld(gid));
	}
	else SetPlayerPos(playerid,x+1,y,z);

	new tstr[180];
	format(tstr,180,"{888888}>> {FFFFFF}%s {888888}has teleported to {FFFFFF}%s",Player[playerid][Name],Player[gid][Name]);
	SendClientMessageToAll(-1,tstr);

	return 1;
}

CMD:spec(playerid, params[])
{
	if(isnull(params)) return SendClientMessage(playerid,-1,"{888888}>> {FFFFFF}Usage: {888888}/spec [Player ID]");
	new specid = strval(params);
	if(!IsPlayerConnected(specid)) return SendClientMessage(playerid,-1,"{888888}>> {FFFFFF}Error: {888888}That player isn't connected.");
	if(specid == playerid) return SendClientMessage(playerid,-1,"{888888}>> {FFFFFF}Error: {888888}Can't spectate yourself.");
	if(Player[playerid][Playing] == true) return SendClientMessage(playerid,-1,"{888888}>> {FFFFFF}Error: {888888}Can't spectate while you are playing.");
	if(Player[specid][Spectating] == true) return SendClientMessage(playerid,-1,"{888888}>> {FFFFFF}Error: {888888}That player is spectating someone else.");
	if(GetPlayerState(specid) != 1 && GetPlayerState(specid) != 2 && GetPlayerState(specid) != 3) return SendClientMessage(playerid,-1,"{888888}>> {FFFFFF}Error: {888888}That player is not spawned.");
	if(Current != -1 && !IsTeamTheSame(Player[specid][Team], Player[playerid][Team])) return SendClientMessage(playerid,-1,"{888888}>> {FFFFFF}Error: {888888}You can only spectate your own team.");

	if(Player[playerid][InDM] == true) {
	    Player[playerid][InDM] = false;
		Player[playerid][DMReadd] = 0;
	}
	
	SpectatePlayer(playerid, specid);
	return 1;
}

CMD:specoff(playerid, params[])
{
	if(Player[playerid][Spectating] == false) return 1;
	
	StopSpectate(playerid);
	return 1;
}

CMD:kill(playerid, params[])
{
	SetPlayerHealth(playerid, 0.0);
	return 1;
}


CMD:car(playerid, params[])
{
	if(isnull(params)) return SendClientMessage(playerid,-1,"{888888}>> {FFFFFF}Usage: {888888}/car [Vehicle Name or Vehicle ID]");
	if(Player[playerid][InDM] == true) return SendClientMessage(playerid,-1,"{888888}>> {FFFFFF}Error: {888888}You can't spawn vehicle in DM.");

	new veh = GetVehicleModelID(params);
    if(veh < 400 || veh > 611) return SendClientMessage(playerid,-1,"{888888}>> {FFFFFF}Error: {888888}Invalid Vehicle ID."); //In samp there is no vehile with ID below 400 or above 611
	
	//Block some vehiles that u don't like e.g. Tank, hunter. It wil be annoying in lobby. To search for more vehicle IDs try samp wiki.
	if(veh == 432 || veh == 447 || veh == 407 || veh == 430 || veh == 435 || veh == 441 || veh == 447 || veh == 449 || veh == 450 || veh == 464 || veh == 465) return SendClientMessage(playerid, -1, "{888888}>> {EEEEEE}Error: {888888}This vehicle is blocked.");
	if(veh == 472 || veh == 476 || veh == 501 || veh == 512 || veh == 537 || veh == 538 || veh == 544 || veh == 553 || veh == 564 || veh == 569 || veh == 570) return SendClientMessage(playerid, -1, "{888888}>> {EEEEEE}Error: {888888}This vehicle is blocked.");
	if(veh == 577 || veh == 584 || veh == 590 || veh == 591 || veh == 594 || veh == 595 || veh == 601 || veh == 606 || veh == 607 || veh == 608 || veh == 610) return SendClientMessage(playerid, -1, "{888888}>> {EEEEEE}Error: {888888}This vehicle is blocked.");
	if(veh == 611 || veh == 520 || veh == 425 || veh == 476 || veh == 592 || veh == 577 || veh == 592) return SendClientMessage(playerid, -1, "{888888}>> {EEEEEE}Error: {888888}This vehicle is blocked.");


	new Float:Pos[4];
	GetPlayerPos(playerid, Pos[0], Pos[1], Pos[2]);
	GetPlayerFacingAngle(playerid, Pos[3]);
	
	if(Player[playerid][Playing] == true) {
		if(Player[playerid][Team] == DEFENDER || Player[playerid][Team] == REFEREE) return SendClientMessage(playerid, -1, "{888888}>> {EEEEEE}Error: {888888}Only attackers can spawn vehicle.");
        if(BInterior[Current] != 0) return SendClientMessage(playerid, -1, "{888888}>> {EEEEEE}Error: {888888}You can't spawn vehicle in interior base.");
		if(Pos[0] > AttackerSpawn[Current][0] + 100 || Pos[0] < AttackerSpawn[Current][0] - 100 || Pos[1] > AttackerSpawn[Current][1] + 100 || Pos[1] < AttackerSpawn[Current][1] - 100) {
			return SendClientMessage(playerid, -1, "{888888}>> {EEEEEE}Error: {888888}You are too far from attacker spawn."); //If attacker is too far away from his spawn.
		}
	}
	
	if(IsPlayerInAnyVehicle(playerid)) DestroyVehicle(GetPlayerVehicleID(playerid)); //If you are already in a vehicle and use /car, it will destroy that vehicle first and spawn the new one.

 	new MyVehicle = CreateVehicle(veh, Pos[0], Pos[1], Pos[2], Pos[3], -1, -1, -1); //Creates the specific vehicle u were looking for (veh).
    LinkVehicleToInterior(MyVehicle, GetPlayerInterior(playerid)); //Links vehicle interior to the current player interior.
	SetVehicleVirtualWorld(MyVehicle, GetPlayerVirtualWorld(playerid)); //Sets vehicle virtual world the the current virtual world of the player.
	PutPlayerInVehicle(playerid, MyVehicle, 0); //Puts player in the driver seat.


	return 1;
}

CMD:v(playerid, params[])
{
	cmd_car(playerid, params); //This will just go back to /car command. Which means /v and /car are the same and you can use any of the two.
	return 1;
}
	



CMD:startbase(playerid, params[])
{
	if(Player[playerid][Level] < 1) return SendClientMessage(playerid,-1,"{888888}>> {FFFFFF}Error: {888888}You need to be a higher admin level.");
	if(Current != -1) return SendClientMessage(playerid,-1,"{888888}>> {FFFFFF}Error: {888888}A round is in progress, please wait for it to end.");
	if(AllowStartBase == false) return SendClientMessage(playerid,-1,"{888888}>> {FFFFFF}Error: {888888}Please wait.");

	if(isnull(params)) return SendClientMessage(playerid,-1,"{888888}>> {FFFFFF}Usage: {888888}/startbase [Base ID]");
	if(!IsNumeric(params)) return SendClientMessage(playerid,-1,"{888888}>> {FFFFFF}Error: {888888}Base ID can only be numerical.");

	new BaseID = strval(params);

	if(BaseID > MAX_BASES) return SendClientMessage(playerid,-1,"{888888}>> {FFFFFF}Error: {888888}That base does not exist.");
	if(!BExist[BaseID]) return SendClientMessage(playerid,-1,"{888888}>> {FFFFFF}Error: {888888}That base does not exist.");
	
	foreach(new i : Player) {
	    if(Player[i][Team] == ATTACKER || Player[i][Team] == DEFENDER) {
	        TogglePlayerControllable(i, false); // Pause all the players.
		}
	}
	    
	AllowStartBase = false; //Make sure other player or you yourself is not able to start base on top of another base.
	SetTimerEx("OnBaseStart", 4000, false, "i", BaseID);
	
	new String[160];
	format(String, sizeof(String), "{888888}>> {FFFFFF}%s {888888}has started Base: {FFFFFF}%s (ID: %d)", Player[playerid][Name], BName[BaseID], BaseID);
	SendClientMessageToAll(-1, String);
	
	return 1;
}


CMD:sync(playerid, params[])
{
	SyncPlayer(playerid);
	return 1;
}


CMD:getpos(playerid, params[])
{
	new Float:Pos[4], iString[256];
	GetPlayerPos(playerid, Pos[0], Pos[1], Pos[2]);
	GetPlayerFacingAngle(playerid, Pos[3]);
	
	format(iString, sizeof(iString), "X = %.0f, Y = %.0f, Z = %.0f, Facing Angle = %.0f and Interior = %d", Pos[0], Pos[1], Pos[2], Pos[3], GetPlayerInterior(playerid));
	SendClientMessage(playerid, -1, iString);
	
	return 1;
}




CMD:register(playerid, params[])
{
	if(isnull(params)) return SendClientMessage(playerid,-1,"{888888}>> {FFFFFF}Usage: {888888}/register [password]");
	if(Player[playerid][Logged] == true) return SendClientMessage(playerid,-1,"{888888}>> {FFFFFF}Error: {888888}You are already logged in.");
	if(fexist(pProfile(playerid))) return SendClientMessage(playerid,-1,"{888888}>> {FFFFFF}Error: {888888}You are already registered. Use /login");

    dini_Create(pProfile(playerid));

    new HashPass[256];
	WP_Hash(HashPass, sizeof(HashPass), params);
    
    dini_Set(pProfile(playerid),"Password", HashPass);
    dini_IntSet(pProfile(playerid),"Level", 0);
    dini_IntSet(pProfile(playerid),"Weather", MainWeather);
    dini_IntSet(pProfile(playerid),"Time", MainTime);

	Player[playerid][Level] = 0;
	Player[playerid][Weather] = MainWeather;
	Player[playerid][Time] = MainTime;
    Player[playerid][Logged] = true;

	format(HashPass, sizeof(HashPass), "{FFFFFF}>> {888888}You have been successfully registered. {FFFFFF}Password: %s", params);
	SendClientMessage(playerid, -1, HashPass);

	return 1;
}

CMD:login(playerid, params[])
{
	if(isnull(params)) return SendClientMessage(playerid,-1,"{888888}>> {FFFFFF}Usage: {888888}/login [password]");
	if(Player[playerid][Logged] == true) return SendClientMessage(playerid,-1,"{888888}>> {FFFFFF}Error: {888888}You are already logged in.");
	if(!fexist(pProfile(playerid))) return SendClientMessage(playerid,-1,"{888888}>> {FFFFFF}Error: {888888}You haven't registered. Please use {FFFFFF}/register {888888}before login.");

	new CurrentPassword[256];
	CurrentPassword = dini_Get(pProfile(playerid), "Password");

	new HashPass[256];
	WP_Hash(HashPass, sizeof(HashPass), params);

	if(strmatch(CurrentPassword, HashPass)) {
	    Player[playerid][Level] = dini_Int(pProfile(playerid),"Level");
	    Player[playerid][Weather] = dini_Int(pProfile(playerid),"Weather");
        Player[playerid][Time] = dini_Int(pProfile(playerid),"Time");

        SetPlayerWeather(playerid, Player[playerid][Weather]);
        SetPlayerTime(playerid, Player[playerid][Time], 0);

        Player[playerid][Logged] = true;

		format(HashPass, sizeof(HashPass), "{FFFFFF}>> {888888}You have successfullly logged in. {FFFFFF}Level: %d", Player[playerid][Level]);
        SendClientMessage(playerid,-1,HashPass);
	
	} else {
 		SendClientMessage(playerid,-1,"{888888}>> {FFFFFF}Error: {888888}Wrong Password. Please try again.");
	}
	return 1;
}
	
CMD:setlevel(playerid, params[])
{
	if(Player[playerid][Level] < 5 && !IsPlayerAdmin(playerid)) return SendClientMessage(playerid,-1,"{888888}>> {FFFFFF}Error: {888888}You need to be level 5 or rcon admin.");
	new GiveID, LEVEL;
	if(sscanf(params, "id", GiveID, LEVEL)) return SendClientMessage(playerid,-1,"{888888}>> {FFFFFF}Usage: {888888}/setlevel [Playerid] [Level]");

	if(!IsPlayerConnected(GiveID)) return SendClientMessage(playerid,-1,"{888888}>> {FFFFFF}Error: {888888}That player is not connected.");
	if(Player[GiveID][Logged] == false) return SendClientMessage(playerid,-1,"{888888}>> {FFFFFF}Error: {888888}That player is not logged in.");
	if(LEVEL < 0 || LEVEL > 5) return SendClientMessage(playerid,-1,"{888888}>> {FFFFFF}Error: {888888}Invalid level.");
	if(Player[GiveID][Level] == LEVEL) return SendClientMessage(playerid,-1,"{888888}>> {FFFFFF}Error: {888888}That player is already this level.");

	dini_IntSet(pProfile(GiveID), "Level", LEVEL);
	Player[GiveID][Level] = LEVEL;
	
	new iString[256];
	format(iString,sizeof(iString),"{888888}>> {FFFFFF}\"%s\" {888888}has set {FFFFFF}\"%s\"'s {888888}level to: {FFFFFF}%d", Player[playerid][Name], Player[GiveID][Name], LEVEL);
	SendClientMessageToAll(-1, iString);

	return 1;
}


CMD:weather(playerid,params[])
{
    if(isnull(params)) return SendClientMessage(playerid, -1, "{888888}>> {FFFFFF}USAGE: {888888}/weather [ID]");
	if(!IsNumeric(params)) return SendClientMessage(playerid,-1,"{888888}>> {FFFFFF}Error: {888888}You need to put a number for weather id.");
    if(Player[playerid][Logged] == false) return SendClientMessage(playerid,-1,"{888888}>> {FFFFFF}Error: {888888}You need to log in. Use /login");

	new myweather;
	myweather = strval(params);

	SetPlayerWeather(playerid, myweather);
    Player[playerid][Weather] = myweather;

   	dini_IntSet(pProfile(playerid),"Weather",myweather);


    new iString[128];
    format(iString, sizeof(iString), "{FFFFFF}Weather changed to: %d", myweather);
    SendClientMessage(playerid, -1, iString);
    
    return 1;
}

CMD:time(playerid, params[])
{
	if(isnull(params)) return SendClientMessage(playerid, -1, "{888888}>> {FFFFFF}USAGE: {888888}/time [Hour]");
	if(!IsNumeric(params)) return SendClientMessage(playerid,-1,"{888888}>> {FFFFFF}Error: {888888}You need to put a number for weather id.");
    if(Player[playerid][Logged] == false) return SendClientMessage(playerid,-1,"{888888}>> {FFFFFF}Error: {888888}You need to log in.");

	new mytime;
	mytime = strval(params);

	SetPlayerTime(playerid, mytime, 0);
	Player[playerid][Time] = mytime;

	dini_IntSet(pProfile(playerid),"Time",mytime);

    new iString[128];
    format(iString, sizeof(iString), "{FFFFFF}Time changed to: %d", mytime);
    SendClientMessage(playerid, -1, iString);
    return 1;
}

CMD:dm(playerid, params[])
{
	if(isnull(params)) return SendClientMessage(playerid, -1, "{888888}>> {FFFFFF}USAGE: {888888}/dm [DM ID]");
	if(!IsNumeric(params)) return SendClientMessage(playerid, -1, "{888888}>> {FFFFFF}Error: {888888}DM id can only be numeric.");

	new DMID = strval(params);
	
	// Here I also added '=' after '>' so that if the DMID was Bigger than or Equal to MAX_DMS then you get that error message.
	// Without this '=' (equal sign) if you type /dm 15 it will say the command is unkown which is a script error.
	if(DMID >= MAX_DMS) return SendClientMessage(playerid, -1, "{888888}>> {FFFFFF}Error: {888888}Invalid DM id."); // If you don't use this line and later on you use 'crashdetect' plugin for ur gamemode, it will give you an error.
	if(DMExist[DMID] == false) return SendClientMessage(playerid, -1, "{888888}>> {FFFFFF}Error: {888888}This DM does not exist.");


	ResetPlayerWeapons(playerid); // Reset all player weapons
	SetPlayerVirtualWorld(playerid, 1); // Put player in a different virtual world so that if you create a DM in your lobby and you join the DM, you won't be able to see other players in the lobby.
	SetPlayerHealth(playerid, 100);
	SetPlayerArmour(playerid, 100);

	// format for SetPlayerSpawn(Playerid, Team, Skin, X, Y, X, Angle, Weapon 1, Weapon 1 Ammo, Weapon 2, Weapon 2 Ammo, Weapon 3, Weapon 3 Ammo)
	// I suggest you use SetPlayerSpawn most of the time instead of 'SetPlayerPos' And 'SetPlayerSkin' because using 'SetPlayerSkin' and 'SpawnPlayer' at the same time will crash the player in random even if the player has 100% orginal GTA. 
	SetSpawnInfo(playerid, playerid, Skin[Player[playerid][Team]], DMSpawn[DMID][0], DMSpawn[DMID][1], DMSpawn[DMID][2], DMSpawn[DMID][3], DMWeapons[DMID][0], 9999, DMWeapons[DMID][1], 9999, DMWeapons[DMID][2], 9999);
	SetPlayerInterior(playerid, DMInterior[DMID]);
	
	new iString[140];

    if(DMWeapons[DMID][1] == 0 && DMWeapons[DMID][2] == 0) format(iString, sizeof(iString), "{888888}>> {FFFFFF}%s {888888}has joined DM %d {FFFFFF}(%s).", Player[playerid][Name], DMID, WeaponNames[DMWeapons[DMID][0]]); // If the second and third weapons are punch or no weapons then it'll show you just one weapon instead of saying (Deagle - Punch - Punch)
	else if(DMWeapons[DMID][2] == 0) format(iString, sizeof(iString), "{888888}>> {FFFFFF}%s {888888}has joined DM %d {FFFFFF}(%s - %s).", Player[playerid][Name], DMID, WeaponNames[DMWeapons[DMID][0]], WeaponNames[DMWeapons[DMID][1]]); //If only the third weapons is punch then it'll show two weapons e.g. (Deagle - Shotgun) instead of (Deagle - Shotgun - Punch)
	else format(iString, sizeof(iString), "{888888}>> {FFFFFF}%s {888888}has joined DM %d {FFFFFF}(%s - %s - %s).", Player[playerid][Name], DMID, WeaponNames[DMWeapons[DMID][0]], WeaponNames[DMWeapons[DMID][1]], WeaponNames[DMWeapons[DMID][2]] ); //If all the weapons are known then it'll show u all three weapons e.g. (Deagle - Shotgun - Sniper)

	SendClientMessageToAll(-1, iString); // Send the formatted message to everyone.
	
	Player[playerid][IgnoreSpawn] = true; //Make sure you ignore OnPlayerSpawn, else you will just spawn in lobby (because u are about to use SpawnPlayerEx).
	SpawnPlayerEx(playerid); //Spawns players, in this case we have SetSpawnInfo (but still you need to make sure OnPlayerSpawn is ignored);

	Player[playerid][InDM] = true; // Keep a record of what is the player current status.
	Player[playerid][DMReadd] = DMID;

	if(Player[playerid][BeingSpeced] == true) {
	    foreach(new i : Player) {
	        if(Player[i][Spectating] == true && Player[i][IsSpectatingID] == playerid) {
	            StopSpectate(i);
			}
		}
	}

	return 1;
}



CMD:dmq(playerid, params[])
{
	QuitDM(playerid);
	return 1;
	
}


SpawnInDM(playerid, DMID)
{
	ResetPlayerWeapons(playerid); // Reset all player weapons
	SetPlayerVirtualWorld(playerid, 1); // Put player in a different virtual world so that if you create a DM in your lobby and you join the DM, you won't be able to see other players in the lobby.
	SetPlayerHealth(playerid, 100);
	SetPlayerArmour(playerid, 100);

	SetSpawnInfo(playerid, playerid, Skin[Player[playerid][Team]], DMSpawn[DMID][0], DMSpawn[DMID][1], DMSpawn[DMID][2], DMSpawn[DMID][3], DMWeapons[DMID][0], 9999, DMWeapons[DMID][1], 9999, DMWeapons[DMID][2], 9999);
	SetPlayerInterior(playerid, DMInterior[DMID]);
	
	Player[playerid][IgnoreSpawn] = true; //Make sure you ignore OnPlayerSpawn, else you will just spawn in lobby (because u are about to use SpawnPlayerEx).
	SpawnPlayerEx(playerid); //Spawns players, in this case we have SetSpawnInfo (but still you need to make sure OnPlayerSpawn is ignored);

    Player[playerid][InDM] = true;
}

QuitDM(playerid)
{
    ResetPlayerWeapons(playerid);
    Player[playerid][InDM] = false;
    Player[playerid][DMReadd] = 0;
    SpawnPlayerEx(playerid);
}

//------------------------------------------------------------------------------
// TextDraws
//------------------------------------------------------------------------------

LoadTextDraws()
{
	AttackerText = TextDrawCreate(330.000000, 330.000000, "Attacker");
	TextDrawAlignment(AttackerText, 2);
	TextDrawBackgroundColor(AttackerText,0x00000099);
	TextDrawFont(AttackerText, 1);
	TextDrawLetterSize(AttackerText, 1.100000, 4.000000);
	TextDrawColor(AttackerText, 0xFF000099);
	TextDrawSetOutline(AttackerText, 1);
	TextDrawSetProportional(AttackerText, 1);
	TextDrawSetShadow(AttackerText, 0);

	DefenderText = TextDrawCreate(330.000000, 330.000000, "Defender");
	TextDrawAlignment(DefenderText, 2);
	TextDrawBackgroundColor(DefenderText, 0x00000099);
	TextDrawFont(DefenderText, 1);
	TextDrawLetterSize(DefenderText, 1.100000, 4.000000);
	TextDrawColor(DefenderText, 0x0000FF99);
	TextDrawSetOutline(DefenderText, 1);
	TextDrawSetProportional(DefenderText, 1);
	TextDrawSetShadow(DefenderText, 0);

	RefereeText = TextDrawCreate(330.000000, 330.000000, "Referee");
	TextDrawAlignment(RefereeText, 2);
	TextDrawBackgroundColor(RefereeText, 0x00000099);
	TextDrawFont(RefereeText, 1);
	TextDrawLetterSize(RefereeText, 1.100000, 4.000000);
	TextDrawColor(RefereeText, 0xFFFF0099);
	TextDrawSetOutline(RefereeText, 1);
	TextDrawSetProportional(RefereeText, 1);
	TextDrawSetShadow(RefereeText, 0);

	RoundStats = TextDrawCreate(318.0,431.5,"_");
	TextDrawUseBox(RoundStats,1);
	TextDrawBoxColor(RoundStats,0x0000022);
	TextDrawFont(RoundStats, 1);
	TextDrawTextSize(RoundStats,14.0,640.0);
	TextDrawLetterSize(RoundStats, 0.31, 1.55);
	TextDrawBackgroundColor(RoundStats,0xDDDDDD55);
	TextDrawColor(RoundStats,-65281);
	TextDrawSetOutline(RoundStats,1);
	TextDrawSetShadow(RoundStats,0);
    TextDrawAlignment(RoundStats,2);
    TextDrawSetProportional(RoundStats, 1);

	RoundsPlayed = TextDrawCreate(555.000000, 114.000000, "_");
	TextDrawAlignment(RoundsPlayed, 2);
	TextDrawBackgroundColor(RoundsPlayed, 255);
	TextDrawFont(RoundsPlayed, 1);
	TextDrawLetterSize(RoundsPlayed, 0.330000, 1.65000);
	TextDrawBackgroundColor(RoundsPlayed,0xDDDDDD55);
	TextDrawColor(RoundsPlayed, 16711935);
	TextDrawSetOutline(RoundsPlayed, 1);
	TextDrawSetProportional(RoundsPlayed, 1);
	TextDrawSetShadow(RoundsPlayed,0);
	TextDrawTextSize(RoundsPlayed, 20, 100);
	TextDrawSetSelectable(RoundsPlayed, 1);


    TeamScoreText = TextDrawCreate(557.000000, 100.000000,"_");
	TextDrawFont(TeamScoreText, 1);
	TextDrawLetterSize(TeamScoreText, 0.330000, 1.650000);
	TextDrawBackgroundColor(TeamScoreText,0xDDDDDD55);
	TextDrawColor(TeamScoreText,-65281);
	TextDrawSetOutline(TeamScoreText,1);
    TextDrawSetProportional(TeamScoreText, 1);
    TextDrawAlignment(TeamScoreText,2);
    TextDrawSetShadow(TeamScoreText,0);
	TextDrawTextSize(TeamScoreText, 20, 200);
	TextDrawSetSelectable(TeamScoreText, 1);


//  - End Round TextDraw -

    EN_Attacker = TextDrawCreate(70.000000, 140.000000,"~r~~h~Attacker");
	TextDrawFont(EN_Attacker, 1);
	TextDrawLetterSize(EN_Attacker, 0.5, 2.0);
	TextDrawBackgroundColor(EN_Attacker,0xDDDDDD55);
	TextDrawColor(EN_Attacker,-65281);
	TextDrawSetOutline(EN_Attacker,1);
    TextDrawSetProportional(EN_Attacker, 1);
    TextDrawAlignment(EN_Attacker,1);
    TextDrawSetShadow(EN_Attacker,0);

    EN_Defender = TextDrawCreate(490.000000, 140.000000,"~b~~h~Defender");
	TextDrawFont(EN_Defender, 1);
	TextDrawLetterSize(EN_Defender, 0.5, 2.0);
	TextDrawBackgroundColor(EN_Defender,0xDDDDDD55);
	TextDrawColor(EN_Defender,-65281);
	TextDrawSetOutline(EN_Defender,1);
    TextDrawSetProportional(EN_Defender, 1);
    TextDrawAlignment(EN_Defender,1);
    TextDrawSetShadow(EN_Defender,0);
    
    EN_WhoWon = TextDrawCreate(313.000000, 100.000000,"_");
	TextDrawFont(EN_WhoWon, 1);
	TextDrawLetterSize(EN_WhoWon, 0.5, 2.0);
	TextDrawBackgroundColor(EN_WhoWon,0xDDDDDD55);
	TextDrawColor(EN_WhoWon,-65281);
	TextDrawSetOutline(EN_WhoWon,1);
    TextDrawSetProportional(EN_WhoWon, 1);
    TextDrawAlignment(EN_WhoWon,2);
    TextDrawSetShadow(EN_WhoWon,0);
    
    EN_AttackerDefenderTitle = TextDrawCreate(70.000000, 162.000000,"_");
	TextDrawFont(EN_AttackerDefenderTitle, 1);
	TextDrawLetterSize(EN_AttackerDefenderTitle, 0.25, 1.100000);
	TextDrawBackgroundColor(EN_AttackerDefenderTitle,0xDDDDDD55);
	TextDrawColor(EN_AttackerDefenderTitle,-65281);
	TextDrawSetOutline(EN_AttackerDefenderTitle,1);
    TextDrawSetProportional(EN_AttackerDefenderTitle, 1);
    TextDrawAlignment(EN_AttackerDefenderTitle,1);
    TextDrawSetShadow(EN_AttackerDefenderTitle,0);

    EN_AttackerList = TextDrawCreate(70.000000, 178.000000,"_");
	TextDrawFont(EN_AttackerList, 1);
	TextDrawLetterSize(EN_AttackerList, 0.200000, 1.000000);
	TextDrawBackgroundColor(EN_AttackerList,0xDDDDDD55);
	TextDrawColor(EN_AttackerList,-65281);
	TextDrawSetOutline(EN_AttackerList,1);
    TextDrawSetProportional(EN_AttackerList, 1);
    TextDrawAlignment(EN_AttackerList,1);
    TextDrawSetShadow(EN_AttackerList,0);

    EN_AttackerKills = TextDrawCreate(176.000000, 178.000000,"_");
	TextDrawFont(EN_AttackerKills, 1);
	TextDrawLetterSize(EN_AttackerKills, 0.200000, 1.000000);
	TextDrawBackgroundColor(EN_AttackerKills,0xDDDDDD55);
	TextDrawColor(EN_AttackerKills,-65281);
	TextDrawSetOutline(EN_AttackerKills,1);
    TextDrawSetProportional(EN_AttackerKills, 1);
    TextDrawAlignment(EN_AttackerKills,1);
    TextDrawSetShadow(EN_AttackerKills,0);

    EN_AttackerDeaths = TextDrawCreate(214.000000, 178.000000,"_");
	TextDrawFont(EN_AttackerDeaths, 1);
	TextDrawLetterSize(EN_AttackerDeaths, 0.200000, 1.000000);
	TextDrawBackgroundColor(EN_AttackerDeaths,0xDDDDDD55);
	TextDrawColor(EN_AttackerDeaths,-65281);
	TextDrawSetOutline(EN_AttackerDeaths,1);
    TextDrawSetProportional(EN_AttackerDeaths, 1);
    TextDrawAlignment(EN_AttackerDeaths,1);
    TextDrawSetShadow(EN_AttackerDeaths,0);

    EN_AttackerDamage = TextDrawCreate(261.000000, 178.000000,"_");
	TextDrawFont(EN_AttackerDamage, 1);
	TextDrawLetterSize(EN_AttackerDamage, 0.200000, 1.000000);
	TextDrawBackgroundColor(EN_AttackerDamage,0xDDDDDD55);
	TextDrawColor(EN_AttackerDamage,-65281);
	TextDrawSetOutline(EN_AttackerDamage,1);
    TextDrawSetProportional(EN_AttackerDamage, 1);
    TextDrawAlignment(EN_AttackerDamage,1);
    TextDrawSetShadow(EN_AttackerDamage,0);
/*
    EN_BaseID = TextDrawCreate(314.700000, 178.000000,"_");
	TextDrawFont(EN_BaseID, 1);
	TextDrawLetterSize(EN_BaseID, 0.200000, 1.000000);
	TextDrawBackgroundColor(EN_BaseID,0xDDDDDD55);
	TextDrawColor(EN_BaseID,-65281);
	TextDrawSetOutline(EN_BaseID,1);
    TextDrawSetProportional(EN_BaseID, 1);
    TextDrawAlignment(EN_BaseID,1);
    TextDrawSetShadow(EN_BaseID,0);
*/
    EN_DefenderList = TextDrawCreate(356.5000000, 178.000000,"_");
	TextDrawFont(EN_DefenderList, 1);
	TextDrawLetterSize(EN_DefenderList, 0.200000, 1.000000);
	TextDrawBackgroundColor(EN_DefenderList,0xDDDDDD55);
	TextDrawColor(EN_DefenderList,-65281);
	TextDrawSetOutline(EN_DefenderList,1);
    TextDrawSetProportional(EN_DefenderList, 1);
    TextDrawAlignment(EN_DefenderList,1);
    TextDrawSetShadow(EN_DefenderList,0);

    EN_DefenderKills = TextDrawCreate(459.0000000, 178.000000,"_");
	TextDrawFont(EN_DefenderKills, 1);
	TextDrawLetterSize(EN_DefenderKills, 0.200000, 1.000000);
	TextDrawBackgroundColor(EN_DefenderKills,0xDDDDDD55);
	TextDrawColor(EN_DefenderKills,-65281);
	TextDrawSetOutline(EN_DefenderKills,1);
    TextDrawSetProportional(EN_DefenderKills, 1);
    TextDrawAlignment(EN_DefenderKills,1);
    TextDrawSetShadow(EN_DefenderKills,0);

    EN_DefenderDeaths = TextDrawCreate(500.000000, 178.000000,"_");
	TextDrawFont(EN_DefenderDeaths, 1);
	TextDrawLetterSize(EN_DefenderDeaths, 0.200000, 1.000000);
	TextDrawBackgroundColor(EN_DefenderDeaths,0xDDDDDD55);
	TextDrawColor(EN_DefenderDeaths,-65281);
	TextDrawSetOutline(EN_DefenderDeaths,1);
    TextDrawSetProportional(EN_DefenderDeaths, 1);
    TextDrawAlignment(EN_DefenderDeaths,1);
    TextDrawSetShadow(EN_DefenderDeaths,0);

    EN_DefenderDamage = TextDrawCreate(547.000000, 178.000000,"_");
	TextDrawFont(EN_DefenderDamage, 1);
	TextDrawLetterSize(EN_DefenderDamage, 0.200000, 1.000000);
	TextDrawBackgroundColor(EN_DefenderDamage,0xDDDDDD55);
	TextDrawColor(EN_DefenderDamage,-65281);
	TextDrawSetOutline(EN_DefenderDamage,1);
    TextDrawSetProportional(EN_DefenderDamage, 1);
    TextDrawAlignment(EN_DefenderDamage,1);
    TextDrawSetShadow(EN_DefenderDamage,0);

//  - End of Round Textdraw -

    BaseID_VS = TextDrawCreate(548.000000, 25.000000,"_");
	TextDrawBoxColor(BaseID_VS,255);
	TextDrawFont(BaseID_VS, 1);
	TextDrawLetterSize(BaseID_VS, 0.26000, 1.500000);
	TextDrawBackgroundColor(BaseID_VS,0xDDDDDD55);
	TextDrawColor(BaseID_VS,-65281);
	TextDrawSetOutline(BaseID_VS,1);
    TextDrawSetProportional(BaseID_VS, 1);
    TextDrawSetShadow(BaseID_VS,0);


}

LoadPlayerTextDraws(playerid)
{
	FPSPingPacket[playerid] = CreatePlayerTextDraw(playerid,500.5, 1.4, "_");
	PlayerTextDrawBackgroundColor(playerid, FPSPingPacket[playerid], 0xDDDDDD55);
	PlayerTextDrawFont(playerid, FPSPingPacket[playerid], 1);
    PlayerTextDrawLetterSize(playerid, FPSPingPacket[playerid], 0.190000, 0.93000);
	PlayerTextDrawColor(playerid, FPSPingPacket[playerid], 16711935);
	PlayerTextDrawSetOutline(playerid, FPSPingPacket[playerid], 1);
	PlayerTextDrawSetProportional(playerid, FPSPingPacket[playerid], 1);
	PlayerTextDrawSetShadow(playerid, FPSPingPacket[playerid],0);
	PlayerTextDrawAlignment(playerid, FPSPingPacket[playerid], 1);

	RoundKillDmgTDmg[playerid] = CreatePlayerTextDraw(playerid,3.000000, 387.000000, "_");
	PlayerTextDrawFont(playerid, RoundKillDmgTDmg[playerid], 1);
	PlayerTextDrawLetterSize(playerid, RoundKillDmgTDmg[playerid], 0.200000, 0.900000);
	PlayerTextDrawBackgroundColor(playerid, RoundKillDmgTDmg[playerid],0xDDDDDD55);
	PlayerTextDrawColor(playerid, RoundKillDmgTDmg[playerid], 16711935);
	PlayerTextDrawSetOutline(playerid, RoundKillDmgTDmg[playerid], 1);
	PlayerTextDrawSetProportional(playerid, RoundKillDmgTDmg[playerid], 1);
	PlayerTextDrawSetShadow(playerid, RoundKillDmgTDmg[playerid],0);

	DoingDamage[0][playerid] = CreatePlayerTextDraw(playerid,180.0,362.0,"_");
	PlayerTextDrawFont(playerid, DoingDamage[0][playerid], 1);
	PlayerTextDrawLetterSize(playerid, DoingDamage[0][playerid], 0.23000, 1.0);
	PlayerTextDrawBackgroundColor(playerid, DoingDamage[0][playerid],0xDDDDDD55);
	PlayerTextDrawColor(playerid, DoingDamage[0][playerid], 16727295);
	PlayerTextDrawSetProportional(playerid, DoingDamage[0][playerid], 1);
	PlayerTextDrawSetOutline(playerid, DoingDamage[0][playerid],1);
    PlayerTextDrawSetShadow(playerid, DoingDamage[0][playerid],0);

	DoingDamage[1][playerid] = CreatePlayerTextDraw(playerid,180.0,372.0,"_");
	PlayerTextDrawFont(playerid, DoingDamage[1][playerid], 1);
	PlayerTextDrawLetterSize(playerid, DoingDamage[1][playerid], 0.23000, 1.0);
	PlayerTextDrawBackgroundColor(playerid, DoingDamage[1][playerid],0xDDDDDD55);
	PlayerTextDrawColor(playerid, DoingDamage[1][playerid], 16727295);
	PlayerTextDrawSetProportional(playerid, DoingDamage[1][playerid], 1);
	PlayerTextDrawSetOutline(playerid, DoingDamage[1][playerid],1);
    PlayerTextDrawSetShadow(playerid, DoingDamage[1][playerid],0);

	DoingDamage[2][playerid] = CreatePlayerTextDraw(playerid,180.0,382.0,"_");
	PlayerTextDrawFont(playerid, DoingDamage[2][playerid], 1);
	PlayerTextDrawLetterSize(playerid, DoingDamage[2][playerid], 0.23000, 1.0);
	PlayerTextDrawBackgroundColor(playerid, DoingDamage[2][playerid],0xDDDDDD55);
	PlayerTextDrawColor(playerid, DoingDamage[2][playerid], 16727295);
	PlayerTextDrawSetProportional(playerid, DoingDamage[2][playerid], 1);
	PlayerTextDrawSetOutline(playerid, DoingDamage[2][playerid],1);
    PlayerTextDrawSetShadow(playerid, DoingDamage[2][playerid],0);

	GettingDamaged[0][playerid] = CreatePlayerTextDraw(playerid,400.0,362.0,"_");
	PlayerTextDrawFont(playerid, GettingDamaged[0][playerid], 1);
	PlayerTextDrawLetterSize(playerid, GettingDamaged[0][playerid], 0.23000, 1.0);
	PlayerTextDrawBackgroundColor(playerid, GettingDamaged[0][playerid],0xDDDDDD55);
	PlayerTextDrawColor(playerid, GettingDamaged[0][playerid], 16727295);
	PlayerTextDrawSetProportional(playerid, GettingDamaged[0][playerid], 1);
	PlayerTextDrawSetOutline(playerid, GettingDamaged[0][playerid],1);
	PlayerTextDrawSetShadow(playerid, GettingDamaged[0][playerid],0);

	GettingDamaged[1][playerid] = CreatePlayerTextDraw(playerid,400.0,372.0,"_");
	PlayerTextDrawFont(playerid, GettingDamaged[1][playerid], 1);
	PlayerTextDrawLetterSize(playerid, GettingDamaged[1][playerid], 0.23000, 1.0);
	PlayerTextDrawBackgroundColor(playerid, GettingDamaged[1][playerid],0xDDDDDD55);
	PlayerTextDrawColor(playerid, GettingDamaged[1][playerid], 16727295);
	PlayerTextDrawSetProportional(playerid, GettingDamaged[1][playerid], 1);
	PlayerTextDrawSetOutline(playerid, GettingDamaged[1][playerid],1);
	PlayerTextDrawSetShadow(playerid, GettingDamaged[1][playerid],0);

	GettingDamaged[2][playerid] = CreatePlayerTextDraw(playerid,400.0,382.0,"_");
	PlayerTextDrawFont(playerid, GettingDamaged[2][playerid], 1);
	PlayerTextDrawLetterSize(playerid, GettingDamaged[2][playerid], 0.23000, 1.0);
	PlayerTextDrawBackgroundColor(playerid, GettingDamaged[2][playerid],0xDDDDDD55);
	PlayerTextDrawColor(playerid, GettingDamaged[2][playerid], 16727295);
	PlayerTextDrawSetProportional(playerid, GettingDamaged[2][playerid], 1);
	PlayerTextDrawSetOutline(playerid, GettingDamaged[2][playerid],1);
	PlayerTextDrawSetShadow(playerid, GettingDamaged[2][playerid],0);

	RoundText[playerid] = CreatePlayerTextDraw(playerid, 318.0,431.5,"_");
	PlayerTextDrawUseBox(playerid, RoundText[playerid], 1);
	PlayerTextDrawBoxColor(playerid, RoundText[playerid], 0x00000022);
	PlayerTextDrawFont(playerid, RoundText[playerid], 1);
	PlayerTextDrawTextSize(playerid, RoundText[playerid], 14.0,640.0);
	PlayerTextDrawLetterSize(playerid, RoundText[playerid], 0.31, 1.55);
	PlayerTextDrawBackgroundColor(playerid, RoundText[playerid], 0xDDDDDD55);
	PlayerTextDrawColor(playerid, RoundText[playerid], -65281);
	PlayerTextDrawSetOutline(playerid, RoundText[playerid], 1);
	PlayerTextDrawSetShadow(playerid, RoundText[playerid], 0);
    PlayerTextDrawAlignment(playerid, RoundText[playerid], 2);
    PlayerTextDrawSetProportional(playerid, RoundText[playerid], 1);

	WhoSpec[0][playerid] = CreatePlayerTextDraw(playerid,520, 300.000000, "_");
	PlayerTextDrawBackgroundColor(playerid, WhoSpec[0][playerid], 0xDDDDDD55);
	PlayerTextDrawFont(playerid, WhoSpec[0][playerid], 1);
	PlayerTextDrawLetterSize(playerid, WhoSpec[0][playerid], 0.240000, 0.899999);
	PlayerTextDrawColor(playerid, WhoSpec[0][playerid], -65281);
	PlayerTextDrawSetOutline(playerid, WhoSpec[0][playerid], 1);
	PlayerTextDrawSetProportional(playerid, WhoSpec[0][playerid], 1);
	PlayerTextDrawSetShadow(playerid, WhoSpec[0][playerid], 0);

	WhoSpec[1][playerid] = CreatePlayerTextDraw(playerid,520, 349.000000, "_");
	PlayerTextDrawBackgroundColor(playerid, WhoSpec[1][playerid], 0xDDDDDD55);
	PlayerTextDrawFont(playerid, WhoSpec[1][playerid], 1);
	PlayerTextDrawLetterSize(playerid, WhoSpec[1][playerid], 0.240000, 0.899999);
	PlayerTextDrawColor(playerid, WhoSpec[1][playerid], -65281);
	PlayerTextDrawSetOutline(playerid, WhoSpec[1][playerid], 1);
	PlayerTextDrawSetProportional(playerid, WhoSpec[1][playerid], 1);
	PlayerTextDrawSetShadow(playerid, WhoSpec[1][playerid], 0);

	SpecText[0][playerid] = CreatePlayerTextDraw(playerid,8, 358.5, "_");
	PlayerTextDrawFont(playerid, SpecText[0][playerid], 1);
	PlayerTextDrawLetterSize(playerid, SpecText[0][playerid], 0.26000, 1.000000);
	PlayerTextDrawColor(playerid, SpecText[0][playerid], -65281);
	PlayerTextDrawBackgroundColor(playerid, SpecText[0][playerid],0xDDDDDD55);
	PlayerTextDrawSetOutline(playerid, SpecText[0][playerid], 1);
	PlayerTextDrawSetShadow(playerid, SpecText[0][playerid], 0);
	PlayerTextDrawAlignment(playerid, SpecText[0][playerid], 1);

	SpecText[1][playerid] = CreatePlayerTextDraw(playerid,8, 394, "_");
	PlayerTextDrawFont(playerid, SpecText[1][playerid], 1);
	PlayerTextDrawLetterSize(playerid, SpecText[1][playerid], 0.26000, 1.000000);
	PlayerTextDrawColor(playerid, SpecText[1][playerid], -65281);
	PlayerTextDrawBackgroundColor(playerid, SpecText[1][playerid],0xDDDDDD55);
	PlayerTextDrawSetOutline(playerid, SpecText[1][playerid], 1);
	PlayerTextDrawSetShadow(playerid, SpecText[1][playerid], 0);
	PlayerTextDrawAlignment(playerid, SpecText[1][playerid], 1);


}


//------------------------------------------------------------------------------
// Bases, Arenas, DMs and Configs
//------------------------------------------------------------------------------

BaseFile(baseid)
{
	new iString[128];
	format(iString, sizeof(iString),"attackdefend/bases/%d.ini", baseid);
	return iString;
}

DMFile(dmid)
{
	new iString[128];
	format(iString, sizeof(iString),"attackdefend/dms/%d.ini", dmid);
	return iString;
}

LoadBases()
{
    new iString[256], TotalBases;

	for(new i = 0; i < MAX_BASES; i++) {
		if(fexist(BaseFile(i))) {
		    BExist[i] = true;
			TotalBases++;

	    	iString = dini_Get(BaseFile(i),"AttSpawn");
		    sscanf(iString, "p<,>fff", AttackerSpawn[i][0], AttackerSpawn[i][1], AttackerSpawn[i][2]);

			iString = dini_Get(BaseFile(i),"DefSpawn");
			sscanf(iString, "p<,>fff", DefenderSpawn[i][0], DefenderSpawn[i][1], DefenderSpawn[i][2]);

			iString = dini_Get(BaseFile(i),"CPSpawn");
			sscanf(iString, "p<,>fff", CPSpawn[i][0], CPSpawn[i][1], CPSpawn[i][2]);

			iString = dini_Get(BaseFile(i),"Interior");
	    	BInterior[i] = strval(iString);

		    if(!dini_Isset(BaseFile(i), "Name")){
				format(BName[i],256,"No Name");
			}else{
				format(BName[i],256,"%s", dini_Get(BaseFile(i), "Name"));
			}
		}
		else BExist[i] = false;
	}
	
	printf(">> Loaded %d Bases <<", TotalBases);
}

LoadDMs()
{
	new iString[256], TotalDMs;
	
	for(new i = 0; i < MAX_DMS; i++) {
	    if(fexist(DMFile(i))) {
	        DMExist[i] = true;
	        TotalDMs++;
	        
	        iString = dini_Get(DMFile(i), "DMSpawn");
	        sscanf(iString, "p<,>ffff", DMSpawn[i][0], DMSpawn[i][1], DMSpawn[i][2], DMSpawn[i][3]);

			iString = dini_Get(DMFile(i), "DMInterior");
			DMInterior[i] = strval(iString);
			
			iString = dini_Get(DMFile(i), "Wep1");
			DMWeapons[i][0] = strval(iString);

			iString = dini_Get(DMFile(i), "Wep2");
			DMWeapons[i][1] = strval(iString);
			
			iString = dini_Get(DMFile(i), "Wep3");
			DMWeapons[i][2] = strval(iString);
		} else {
		    DMExist[i] = false;
		}
	}

	printf(">> Loaded %d DMs <<", TotalDMs);
}



LoadConfig()
{
	Skin[ATTACKER] 	= 	dini_Int(CONFIG_PATH, "AttackerSkin");
	Skin[DEFENDER] 	= 	dini_Int(CONFIG_PATH, "DefenderSkin");
	Skin[REFEREE] 	= 	dini_Int(CONFIG_PATH, "RefereeSkin");
	MainWeather 	= 	dini_Int(CONFIG_PATH, "ServerWeather");
	MainTime 		= 	dini_Int(CONFIG_PATH, "ServerTime");
	ConfigCPTime    =   dini_Int(CONFIG_PATH, "CPTime");
	ConfigRoundTime =   dini_Int(CONFIG_PATH, "RoundTime");
	TotalRounds     =   dini_Int(CONFIG_PATH, "TotalRound");

	new iString[256];
	iString = dini_Get(CONFIG_PATH, "WeaponLimits");
	sscanf(iString, "p<,>dddddddddd", WeaponLimit[0], WeaponLimit[1], WeaponLimit[2], WeaponLimit[3], WeaponLimit[4], WeaponLimit[5], WeaponLimit[6], WeaponLimit[7], WeaponLimit[8], WeaponLimit[9]);

	iString = dini_Get(CONFIG_PATH, "MainSpawn");
	sscanf(iString, "p<,>ffffd", MainSpawn[0], MainSpawn[1], MainSpawn[2], MainSpawn[3], MainInterior);

	printf("Server Config Loaded.");
}


//------------------------------------------------------------------------------
// Stocks
//------------------------------------------------------------------------------
// You can have all these functions without starting with 'stock'
// If you are sure that you are going to 100 percent use a function then you don't really need to put 'stock'
// However, if you are not sure that you will use a function then put 'stock' otherwise the script will give a warning, asking you that you are not using the function anywhere.

new PLAYER_current_team[MAX_PLAYERS];
stock SAMP_SetPlayerTeam(playerid, teamid)
{
	PLAYER_current_team[playerid] =teamid;
	foreach(new i : Player) {
		SetPlayerTeam(i,PLAYER_current_team[i]);
	}
}

stock ShowEndRoundTextDraw(playerid) {
	TextDrawShowForPlayer(playerid, EN_Attacker);
	TextDrawShowForPlayer(playerid, EN_Defender);
	TextDrawShowForPlayer(playerid, EN_WhoWon);
	TextDrawShowForPlayer(playerid, EN_AttackerDefenderTitle);
	TextDrawShowForPlayer(playerid, EN_AttackerList);
    TextDrawShowForPlayer(playerid, EN_AttackerKills);
    TextDrawShowForPlayer(playerid, EN_AttackerDeaths);
    TextDrawShowForPlayer(playerid, EN_AttackerDamage);
//    TextDrawShowForPlayer(playerid, EN_BaseID);
    TextDrawShowForPlayer(playerid, EN_DefenderList);
    TextDrawShowForPlayer(playerid, EN_DefenderKills);
    TextDrawShowForPlayer(playerid, EN_DefenderDeaths);
    TextDrawShowForPlayer(playerid, EN_DefenderDamage);


	Player[playerid][TextDrawOnScreen] = true;
}

stock HideEndRoundTextDraw(playerid) {
	TextDrawHideForPlayer(playerid, EN_Attacker);
	TextDrawHideForPlayer(playerid, EN_Defender);
	TextDrawHideForPlayer(playerid, EN_WhoWon);
	TextDrawHideForPlayer(playerid, EN_AttackerDefenderTitle);
	TextDrawHideForPlayer(playerid, EN_AttackerList);
    TextDrawHideForPlayer(playerid, EN_AttackerKills);
    TextDrawHideForPlayer(playerid, EN_AttackerDeaths);
    TextDrawHideForPlayer(playerid, EN_AttackerDamage);
//    TextDrawHideForPlayer(playerid, EN_BaseID);
    TextDrawHideForPlayer(playerid, EN_DefenderList);
    TextDrawHideForPlayer(playerid, EN_DefenderKills);
    TextDrawHideForPlayer(playerid, EN_DefenderDeaths);
    TextDrawHideForPlayer(playerid, EN_DefenderDamage);
    
    Player[playerid][TextDrawOnScreen] = false;
    SetCameraBehindPlayer(playerid);
}

stock GetPlayerHighestScores(array[][rankingEnum], left, right)
{
    new
        tempLeft = left,
        tempRight = right,
        pivot = array[(left + right) / 2][player_Score],
        tempVar
    ;
    while(tempLeft <= tempRight)
    {
        while(array[tempLeft][player_Score] > pivot) tempLeft++;
        while(array[tempRight][player_Score] < pivot) tempRight--;

        if(tempLeft <= tempRight)
        {
            tempVar = array[tempLeft][player_Score], array[tempLeft][player_Score] = array[tempRight][player_Score], array[tempRight][player_Score] = tempVar;
            tempVar = array[tempLeft][player_ID], array[tempLeft][player_ID] = array[tempRight][player_ID], array[tempRight][player_ID] = tempVar;
            tempLeft++, tempRight--;
        }
    }
    if(left < tempRight) GetPlayerHighestScores(array, left, tempRight);
    if(tempLeft < right) GetPlayerHighestScores(array, tempLeft, right);
}

stock StorePlayerVariables(playerid) {
	new iString[128];
	for(new i = 0; i < SAVE_SLOTS; i ++){
	   	if(strlen(SaveVariables[i][pName]) < 3){
			format(SaveVariables[i][pName], 24, Player[playerid][Name]);

	       	GetPlayerPos(playerid, SaveVariables[i][pCoords][0],SaveVariables[i][pCoords][1],SaveVariables[i][pCoords][2]);
	 		GetPlayerFacingAngle(playerid, SaveVariables[i][pCoords][3]);

			GetPlayerHealth(playerid,SaveVariables[i][gHealth]);
			GetPlayerArmour(playerid,SaveVariables[i][gArmour]);

	        SaveVariables[i][pTeam] 	= 	Player[playerid][Team];
	        SaveVariables[i][pInterior] = 	GetPlayerInterior(playerid);
			SaveVariables[i][pSkin] 	= 	Skin[Player[playerid][pTeam]];
	        SaveVariables[i][pVWorld] 	= 	GetPlayerVirtualWorld(playerid);

			SaveVariables[i][RKills]   	=  	Player[playerid][RoundKills];
			SaveVariables[i][RDeaths]  	= 	Player[playerid][RoundDeaths];
			SaveVariables[i][RDamage] 	= 	Player[playerid][RoundDamage];
			SaveVariables[i][TKills]   	=  	Player[playerid][TotalKills];
			SaveVariables[i][TDeaths]  	= 	Player[playerid][TotalDeaths];
			SaveVariables[i][TDamage] 	= 	Player[playerid][TotalDamage];
			
			SaveVariables[i][RoundID]   =   Current;

			for(new slots = 0; slots < 13; slots++){
				GetPlayerWeaponData(playerid,slots,SaveVariables[i][pWeapons][slots],SaveVariables[i][pAmmo][slots]);
			}

	        format(iString,sizeof(iString),"{FFFFFF}>> {888888}Successfully saved {FFFFFF}%s {888888}variables.", PNames[playerid]);
	    	SendClientMessageToAll(-1, iString);
	    	break;
        } else continue;
	}
}

stock LoadPlayerVariables(playerid)
{
	for(new i = 0; i < SAVE_SLOTS; i ++) {
		if( strlen( SaveVariables[i][pName] ) > 3 && strcmp( SaveVariables[i][pName], Player[playerid][Name], true ) == 0 ) {
			if(SaveVariables[i][RoundID] != Current) return 1;

			Player[playerid][Playing] = true;
			Player[playerid][WasInBase] = true;

			SetPlayerInterior(playerid, SaveVariables[i][pInterior]);
			SetPlayerVirtualWorld(playerid, SaveVariables[i][pVWorld]);
			SetPlayerHealth(playerid,SaveVariables[i][gHealth]);
			SetPlayerArmour(playerid,SaveVariables[i][gArmour]);
			SetPlayerSkin(playerid, SaveVariables[i][pSkin]);
	        Player[playerid][Team] = SaveVariables[i][pTeam];

			Player[playerid][RoundKills] 	= 	SaveVariables[i][RKills];
			Player[playerid][RoundDeaths] 	= 	SaveVariables[i][RDeaths];
			Player[playerid][RoundDamage] 	= 	SaveVariables[i][RDamage];
			Player[playerid][TotalKills] 	= 	SaveVariables[i][TKills];
			Player[playerid][TotalDeaths] 	= 	SaveVariables[i][TDeaths];
			Player[playerid][TotalDamage] 	= 	SaveVariables[i][TDamage];
			
			ColorFix(playerid);

			SetSpawnInfo(playerid, Player[playerid][Team], Skin[Player[playerid][Team]], SaveVariables[i][pCoords][0], SaveVariables[i][pCoords][1], SaveVariables[i][pCoords][2]+1, SaveVariables[i][pCoords][3], 0, 0, 0, 0, 0, 0);
			Player[playerid][IgnoreSpawn] = true;
			SpawnPlayer(playerid);

            SetCameraBehindPlayer(playerid);
	
			for(new slots = 0; slots < 13; slots++){
				GivePlayerWeapon(playerid,SaveVariables[i][pWeapons][slots],SaveVariables[i][pAmmo][slots]);
            }
	

			SaveVariables[i][pSkin] = 0;
			
	        SaveVariables[i][pCoords][0] = 0.0;
			SaveVariables[i][pCoords][1] = 0.0;
			SaveVariables[i][pCoords][2] = 0.0;
			SaveVariables[i][pCoords][3] = 0.0;

			format(SaveVariables[i][pName], 24," ");

			SaveVariables[i][gHealth] = 0.0;
			SaveVariables[i][gArmour] = 0.0;
			SaveVariables[i][pInterior] = 0;
			SaveVariables[i][pVWorld] = 0;
	        SaveVariables[i][pTeam] = 0;
            SaveVariables[i][RKills] = 0;
			SaveVariables[i][RDeaths] = 0;
            SaveVariables[i][RDamage] = 0;
            SaveVariables[i][TKills] = 0;
            SaveVariables[i][TDeaths] = 0;
            SaveVariables[i][TDamage] = 0;

			for(new slots = 0; slots < 13; slots++) {
				SaveVariables[i][pWeapons][slots] = 0;
				SaveVariables[i][pAmmo][slots] = 0;
			}

			new string[256];
	        format(string,256,"{FFFFFF}>> {888888}Re-added player {FFFFFF}%s. {888888}Variables successfully loaded.", Player[playerid][Name]);
	    	SendClientMessageToAll(-1, string);

	    	return 1;
		}
	}
	return 1;
}

stock ClearPlayerVariables()
{
	for(new i = 0; i < SAVE_SLOTS; i ++) {

		format(SaveVariables[i][pName], 24," ");

		SaveVariables[i][pSkin] = 0;
        SaveVariables[i][pCoords][0] = 0.0;
		SaveVariables[i][pCoords][1] = 0.0;
		SaveVariables[i][pCoords][2] = 0.0;
		SaveVariables[i][pCoords][3] = 0.0;

		SaveVariables[i][gHealth] = 0.0;
		SaveVariables[i][gArmour] = 0.0;
		SaveVariables[i][pInterior] = 0;
		SaveVariables[i][pVWorld] = 0;
        SaveVariables[i][pTeam] = 0;
        SaveVariables[i][RKills] = 0;
		SaveVariables[i][RDeaths] = 0;
        SaveVariables[i][RDamage] = 0;
        SaveVariables[i][TKills] = 0;
        SaveVariables[i][TDeaths] = 0;
        SaveVariables[i][TDamage] = 0;

		for(new slots = 0; slots < 13; slots++) {
			SaveVariables[i][pWeapons][slots] = 0;
			SaveVariables[i][pAmmo][slots] = 0;
		}
	}
}

stock IsTeamTheSame(team1, team2)
{
	if(team1 == team2)
	    return true;
	else if((team1 == DEFENDER || team2 == DEFENDER) && (team1 == DEFENDER_SUB || team2 == DEFENDER_SUB))
		return true;
	else if((team1 == ATTACKER || team2 == ATTACKER) && (team1 == ATTACKER_SUB || team2 == ATTACKER_SUB))
		return true;
	else
	    return false;
}

stock SpecWeapons(playerid){
    new WeaponString[128];
	new WeaponID2, Ammo2;
	for(new i = 0; i < 13; i++){
	    if(i == 0 || i == 1){
	   		GetPlayerWeaponData(playerid,i,WeaponID2,Ammo2);
	   		if(Ammo2 > 1){
			    Ammo2 = 1;
			}
	    } else {
	   		GetPlayerWeaponData(playerid,i,WeaponID2,Ammo2);
		}
		if(WeaponID2 > 0 && Ammo2 > 0) {
		    if(Ammo2 > 60000)
		        Ammo2 = 1;
		    if(strlen(WeaponString) > 4) {
				format(WeaponString,sizeof(WeaponString),"%s~r~~h~, ~l~~h~%s", WeaponString, WeaponNames[WeaponID2]);
			} else {
				format(WeaponString,sizeof(WeaponString),"~l~~h~%s", WeaponNames[WeaponID2]);
			}
		}
	}
	if(strlen(WeaponString) < 3) {
		WeaponString = "~l~~h~Fist";
	}
	return WeaponString;
}

stock RemoveClanTagFromName(playerid) {
    new start, end, string[MAX_PLAYER_NAME];
    format(string, MAX_PLAYER_NAME, "%s", Player[playerid][Name]);
    start = strfind(string, "[", true);
    end = strfind(string, "]", true);
    if (start >= end){
		return string;
    }else{
        strdel(string, start, end + 1);
        return string;
    }
}

stock ColorFix(playerid) {
	if(Player[playerid][Playing] == true) {
	    switch(Player[playerid][Team]) {
	        case ATTACKER: SetPlayerColor(playerid, ATTACKER_PLAYING);
	        case DEFENDER: SetPlayerColor(playerid, DEFENDER_PLAYING);
	        case REFEREE: SetPlayerColor(playerid, REFEREE_COLOR);
		}
	} else {
	    switch(Player[playerid][Team]) {
	        case ATTACKER: SetPlayerColor(playerid, ATTACKER_NOT_PLAYING);
	        case DEFENDER: SetPlayerColor(playerid, DEFENDER_NOT_PLAYING);
	        case REFEREE: SetPlayerColor(playerid, REFEREE_COLOR);
	        case ATTACKER_SUB: SetPlayerColor(playerid, ATTACKER_SUB_COLOR);
	        case DEFENDER_SUB: SetPlayerColor(playerid, DEFENDER_SUB_COLOR);
		}
	}
}

stock RadarFix() {
    foreach(new i : Player) {
		foreach(new x : Player) {
		    if(Player[i][Playing] == true && Player[x][Playing] == true) {
				if(Player[x][Team] != Player[i][Team]) {
					SetPlayerMarkerForPlayer(x,i,GetPlayerColor(i) & 0xFFFFFF00);
	            } else {
					SetPlayerMarkerForPlayer(x,i,GetPlayerColor(i) | 0x00000055);
				}
			} else if(Player[i][Playing] == false && Player[x][Playing] == true) {
				if(Player[x][Team] != Player[i][Team]) {
					SetPlayerMarkerForPlayer(x,i,GetPlayerColor(i) & 0xFFFFFF00);
	            } else {
					SetPlayerMarkerForPlayer(x,i,GetPlayerColor(i) | 0x00000055);
				}
			}
		}
    }
}

	        

stock ClearChat() {
	for(new i = 0; i <= 10; i++) {
	    SendClientMessageToAll(-1, " ");
	}
}

stock GetVehicleModelID(vehiclename[])
{
	for(new i = 0; i < 211; i++){
        if(strfind(aVehicleNames[i], vehiclename, true) != -1)
        return i + 400;
    } return -1;
}

stock ClearKillList() {
	for(new i = 0; i < 5; i++) {
	    SendDeathMessage(255, 50, 255);
	}
}

stock DestroyAllVehicles() {
	for(new i = 0; i < MAX_VEHICLES; i++) {
	    DestroyVehicle(i);
	}
}

SyncPlayer(playerid)
{
	if(Player[playerid][Syncing] == true) return 1;
	if(IsPlayerInAnyVehicle(playerid)) return 1;
	
	Player[playerid][Syncing] = true;
	SetTimerEx("SyncInProgress", 1000, false, "i", playerid);

	new Float:HP[2], Float:Pos[4], Int, VirtualWorld;
	GetPlayerHealth(playerid, HP[0]);
	GetPlayerArmour(playerid, HP[1]);

//	new Float:Vel[3]; // Velocity is float so make sure you have "Float:" before the variable. I forgot to mention in the Video
//	GetPlayerVelocity(playerid, Vel[0], Vel[1], Vel[2]);
	
	
	GetPlayerPos(playerid, Pos[0], Pos[1], Pos[2]);
	GetPlayerFacingAngle(playerid, Pos[3]);
	
	Int = GetPlayerInterior(playerid);
	VirtualWorld = GetPlayerVirtualWorld(playerid);
	
	new Weapons[13][2];
	for(new i = 0; i < 13; i++) {
	    GetPlayerWeaponData(playerid, i, Weapons[i][0], Weapons[i][1]);
	}
	
	ClearAnimations(playerid);
	Player[playerid][IgnoreSpawn] = true;
	
	SetSpawnInfo(playerid, GetPlayerTeam(playerid), Skin[Player[playerid][Team]], Pos[0], Pos[1], Pos[2]-0.4, Pos[3], 0, 0, 0, 0, 0, 0);
	SpawnPlayerEx(playerid);
	
	SetPlayerHealth(playerid, HP[0]);
	SetPlayerArmour(playerid, HP[1]);
	
	SetPlayerInterior(playerid, Int);
	SetPlayerVirtualWorld(playerid, VirtualWorld);
	
//	SetPlayerVelocity(playerid, Vel[0], Vel[1], Vel[2]);
	
	for(new i = 0; i < 13; i++) {
	    GivePlayerWeapon(playerid, Weapons[i][0], Weapons[i][1]);
	}
	
	return 1;
}
	


SpawnPlayerEx(playerid)
{
	if(IsPlayerInAnyVehicle(playerid)) RemovePlayerFromVehicle(playerid);
	SetPlayerPos(playerid, 0, 0, 0);
	SpawnPlayer(playerid);
}

stock IsNumeric(string[]){
    for (new i = 0, j = strlen(string); i < j; i++){
            if (string[i] > '9' || string[i] < '0') return 0;
    }
    return 1;
}


stock strmatch(const sStr1[], const sStr2[]) {
	return (strcmp(sStr1, sStr2, true) == 0) && (strlen(sStr2) == strlen(sStr1)) ? true : false;
}

stock Float:GetPlayerPacketLoss(playerid) {

    new stats[401], stringstats[70];
    GetPlayerNetworkStats(playerid, stats, sizeof(stats));
    new len = strfind(stats, "Packetloss: ");
    new Float:packetloss = 0.0;
    if(len != -1) {
        strmid(stringstats, stats, len, strlen(stats));
        new len2 = strfind(stringstats, "%");
        if(len != -1) {
            strdel(stats, 0, strlen(stats));
            strmid(stats, stringstats, len2-3, len2);
            packetloss = floatstr(stats);
            }
    }
    return packetloss;
}


stock GetPlayerFPS(playerid) {
	new drunk2 = GetPlayerDrunkLevel(playerid);
	if(drunk2 < 100){
	    SetPlayerDrunkLevel(playerid,2000);
	}else{
	    if(Player[playerid][DLlast] != drunk2){
	        new fps = Player[playerid][DLlast] - drunk2;
	        if((fps > 0) && (fps < 200))
   			Player[playerid][FPS] = fps;
			Player[playerid][DLlast] = drunk2;
		}
	}
}


stock pProfile(playerid) {
	new String[128];
	format(String, sizeof(String), "attackdefend/users/%s.ini", Player[playerid][Name]);
	return String;
}





//------------------------------------------------------------------------------
// Script update per second And Forward Scripts
//------------------------------------------------------------------------------
// When a function is called from a timer you always have to 'forward' first and then 'public'

forward OnScriptUpdate();
public OnScriptUpdate()
{
	new Alive[2];

	foreach(new i : Player) {
        GetPlayerFPS(i);
        
		new iString[160];

		GetPlayerHealth(i, Player[i][pHealth]);
		GetPlayerArmour(i, Player[i][pArmour]);
		ResetPlayerMoney(i);
		GivePlayerMoney(i, -floatround(Player[i][pHealth] + Player[i][pArmour]));

		new pPing = GetPlayerPing(i);
		new Float:pPacket = GetPlayerPacketLoss(i);

		format(iString,sizeof(iString),"~l~~h~FPS %s~h~%d			~l~~h~Ping %s~h~%d			~l~~h~PacketLoss %s~h~%.1f%%",TDC[Player[i][Team]], Player[i][FPS], TDC[Player[i][Team]], pPing, TDC[Player[i][Team]], pPacket);
		PlayerTextDrawSetString(i, FPSPingPacket[i],iString);

		if(PlayersInCP > 0 && Current != -1) PlayerPlaySound(i,1056,0.0,0.0,0.0);

		if(Player[i][Spectating] == true && Player[i][IsSpectatingID] != INVALID_PLAYER_ID) {
			format(iString,sizeof(iString),"~l~~h~%s ~r~~h~%d~n~~l~~h~(~w~%.0f~l~~h~)  ~l~~h~(~r~~h~%.0f~l~~h~)~n~~l~~h~Ping ~r~~h~%d ~l~~h~FPS ~r~~h~%d~n~~l~~h~Packet-Loss ~r~~h~%.1f", Player[Player[i][IsSpectatingID]][Name], Player[i][IsSpectatingID], Player[Player[i][IsSpectatingID]][pHealth], Player[Player[i][IsSpectatingID]][pArmour], GetPlayerPing(Player[i][IsSpectatingID]), Player[Player[i][IsSpectatingID]][FPS], GetPlayerPacketLoss(Player[i][IsSpectatingID]));
			PlayerTextDrawSetString(i, SpecText[0][i], iString);
		    PlayerTextDrawShow(i,SpecText[0][i]);

			format(iString,sizeof(iString),"~l~~h~Round Damage ~r~~h~%.0f~n~~l~~h~Total Damage ~r~~h~%.0f~n~~l~~h~%s",Player[Player[i][IsSpectatingID]][RoundDamage], Player[Player[i][IsSpectatingID]][TotalDamage], SpecWeapons(Player[i][IsSpectatingID]));
			PlayerTextDrawSetString(i, SpecText[1][i], iString);
		    PlayerTextDrawShow(i,SpecText[1][i]);
		}
		
		switch(Player[i][Team]) {
		    case ATTACKER: Alive[ATTACKER-1]++;
		    case DEFENDER: Alive[DEFENDER-1]++;
		}
		
		if(TakeDmgCD[0][i] > 0){
			TakeDmgCD[0][i]++;
			if(TakeDmgCD[0][i] == 5) {
				Declared[0][i] = false;
				gLastHit[0][i] = -1;
				HPLost[0][i][H[0][i]] = 0;
				PlayerTextDrawSetString(i, DoingDamage[0][i], "_");
				TakeDmgCD[0][i] = 0;
			}
		} if(TakeDmgCD[1][i] > 0) {
			TakeDmgCD[1][i]++;
			if(TakeDmgCD[1][i] == 5) {
				Declared[1][i] = false;
				gLastHit[1][i] = -2;
				HPLost[0][i][H[1][i]] = 0;
                PlayerTextDrawSetString(i, DoingDamage[1][i], "_");
				TakeDmgCD[1][i] = 0;
			}
		} if(TakeDmgCD[2][i] > 0) {
			TakeDmgCD[2][i]++;
			if(TakeDmgCD[2][i] == 5) {
				HPLost[0][i][H[2][i]] = 0;
                PlayerTextDrawSetString(i, DoingDamage[2][i], "_");
				gLastHit[2][i] = -3;
				TakeDmgCD[2][i] = 0;
			}
		} if(TakeDmgCD[3][i] > 0) {
			TakeDmgCD[3][i]++;
			if(TakeDmgCD[3][i] == 5) {
				Declared[2][i] = false;
				gLastHit[3][i] = -1;
				HPLost[1][i][H[3][i]] = 0;
                PlayerTextDrawSetString(i, GettingDamaged[0][i], "_");
				TakeDmgCD[3][i] = 0;
			}
		}
		if(TakeDmgCD[4][i] > 0) {
			TakeDmgCD[4][i]++;
			if(TakeDmgCD[4][i] == 5) {
				Declared[3][i] = false;
				gLastHit[4][i] = -2;
				HPLost[1][i][H[4][i]] = 0;
                PlayerTextDrawSetString(i, GettingDamaged[1][i], "_");
				TakeDmgCD[4][i] = 0;
			}
		}
		if(TakeDmgCD[5][i] > 0) {
			TakeDmgCD[5][i]++;
			if(TakeDmgCD[5][i] == 5) {
				gLastHit[5][i] = -3;
				HPLost[1][i][H[5][i]] = 0;
                PlayerTextDrawSetString(i, GettingDamaged[2][i], "_");
				TakeDmgCD[5][i] = 0;
			}
		} if(TakeDmgCD[6][i] > 0) {
			TakeDmgCD[6][i]++;
			if(TakeDmgCD[6][i] == 5) {
				ILost[i] = 0;
                PlayerTextDrawSetString(i, GettingDamaged[0][i], "_");
				TakeDmgCD[6][i] = 0;
			}
		} if(TakeDmgCD[7][i] > 0) {
			TakeDmgCD[7][i]++;
			if(TakeDmgCD[7][i] == 5) {
                ILost[i] = 0;
                PlayerTextDrawSetString(i, GettingDamaged[1][i], "_");
				TakeDmgCD[7][i] = 0;
			}
		} if(TakeDmgCD[8][i] > 0) {
			TakeDmgCD[8][i]++;
			if(TakeDmgCD[8][i] == 5) {
                ILost[i] = 0;
				PlayerTextDrawSetString(i, GettingDamaged[2][i], "_");
				TakeDmgCD[8][i] = 0;
			}
		}
	}

	new iString[256];

	if(Current == -1) {
    	format(iString, sizeof(iString), "  ~r~~h~%d  ~l~~h~Vs  ~b~~h~%d", Alive[ATTACKER-1], Alive[DEFENDER-1]);
		TextDrawSetString(BaseID_VS, iString);
	}
	
	if(BaseStarted == true) {
		if(RoundPaused == false) {
			if(PlayersInCP > 0) {
			    CurrentCPTime--;
		    	if(CurrentCPTime == 0) return EndRound(0);
			}
		
		    RoundSeconds--;
		    if(RoundSeconds < 0) {
		        RoundSeconds = 59;
		        RoundMints--;
				if(RoundMints < 0) return EndRound(1);
			}

			if(PlayersAlive[ATTACKER] < 1) return EndRound(2);
			else if(PlayersAlive[DEFENDER] < 1) return EndRound(3);
		}
		
		
		if(PlayersInCP == 0) format(iString,sizeof(iString),"~r~~h~%s  ~r~~h~%d   ~l~~h~(~r~~h~%.0f~l~~h~)			   	            %d:%02d			   	            ~b~~h~%s  ~b~~h~%d   ~l~~h~(~b~~h~%.0f~l~~h~)~n~",TeamName[ATTACKER],PlayersAlive[ATTACKER],TeamHP[ATTACKER],RoundMints,RoundSeconds,TeamName[DEFENDER],PlayersAlive[DEFENDER],TeamHP[DEFENDER]);
		else format(iString,sizeof(iString),"~r~~h~%s  ~r~~h~%d   ~l~~h~(~r~~h~%.0f~l~~h~)			   	            %d:%02d / %d		   	            ~b~~h~%s  ~b~~h~%d   ~l~~h~(~b~~h~%.0f~l~~h~)~n~",TeamName[ATTACKER],PlayersAlive[ATTACKER],TeamHP[ATTACKER],RoundMints,RoundSeconds,CurrentCPTime, TeamName[DEFENDER],PlayersAlive[DEFENDER],TeamHP[DEFENDER]);
		TextDrawSetString(RoundStats, iString);
	}

	return 1;
}



forward SyncInProgress(playerid);
public SyncInProgress(playerid) {
	Player[playerid][Syncing] = false;
}




//------------------------------------------------------------------------------
// Base System
//------------------------------------------------------------------------------

forward OnBaseStart(BaseID);
public OnBaseStart(BaseID)
{
    ClearKillList(); // Clears the kill-list.
    DestroyAllVehicles(); // Destroys (removes) all the spawned vehicles
	Current = BaseID; // Current will be the ID of the base that we just started. We do this so that we can use this ID later on (e.g. check /car command for the use).
    ClearPlayerVariables(); // Clears all saved variables for the crashed players.

	PlayersInCP = 0;
	CurrentCPTime = ConfigCPTime;
    TeamHP[ATTACKER] = 0;
    TeamHP[DEFENDER] = 0;
    PlayersAlive[ATTACKER] = 0;
    PlayersAlive[DEFENDER] = 0;


	foreach(new i : Player) {
		PlayerTextDrawShow(i, RoundText[i]);
		
	    if(Player[i][Team] == ATTACKER || Player[i][Team] == DEFENDER) {

			if(Player[i][InDM] == true) { //Make sure to remove player from DM, otherwise the player will have Player[playerid][Playing] = true and Player[playerid][InDM] = true, so you are saying that the player is both in Base and in DM.
			    Player[i][InDM] = false;
    			Player[i][DMReadd] = 0;
			}

	        SetPlayerVirtualWorld(i, 2); //Set player virtual world to something different that that for lobby and DM so that they don't collide with each other. e.g. You shouldn't be able to see players in lobby or DM while you are in base.
	        SetPlayerInterior(i, BInterior[Current]);
			TogglePlayerControllable(i, false); //Pause players.
			SetPlayerPos(i, CPSpawn[Current][0], CPSpawn[Current][1], CPSpawn[Current][2]);
			SetPlayerCheckpoint(i, CPSpawn[Current][0], CPSpawn[Current][1], CPSpawn[Current][2], 2); // Set checkpoint location and size.

		}
		
		Player[i][WasInCP] = false;
	}


	ViewTimer = 4;
	ViewBaseForPlayers();

	new iString[160];
	format(iString, sizeof(iString), "mapname Base: %d", Current); //Will change the map name in samp.exe to your base id (e.g. Base: 4)
	SendRconCommand(iString);

	format(iString, sizeof(iString), "~l~~h~Base (~r~~h~%d~l~~h~)", Current);
	TextDrawSetString(BaseID_VS, iString);
}


forward ViewBaseForPlayers();
public ViewBaseForPlayers()
{
	ViewTimer--;

	if(ViewTimer == 0) {
	    SpawnPlayersInBase();
	    return 1;
	}

	foreach(new i : Player) {
	    if(Player[i][Team] == ATTACKER || Player[i][Team] == DEFENDER) {
	        PlayerPlaySound(i,1056,0.0,0.0,0.0);
	        switch(ViewTimer) {
			    case 4: {
					SetPlayerCameraLookAt(i,CPSpawn[Current][0],CPSpawn[Current][1],CPSpawn[Current][2]);
	    	   		SetPlayerCameraPos(i,CPSpawn[Current][0]+100,CPSpawn[Current][1],CPSpawn[Current][2]+80);
				} case 3: {
	  	   			SetPlayerCameraLookAt(i,CPSpawn[Current][0],CPSpawn[Current][1],CPSpawn[Current][2]);
	    	   		SetPlayerCameraPos(i,CPSpawn[Current][0],CPSpawn[Current][1]+100,CPSpawn[Current][2]+80);
				} case 2: {
	    	   		SetPlayerCameraLookAt(i,CPSpawn[Current][0],CPSpawn[Current][1],CPSpawn[Current][2]);
	    	   		SetPlayerCameraPos(i,CPSpawn[Current][0]-100,CPSpawn[Current][1],CPSpawn[Current][2]+80);
				} case 1: {
	    	   		SetPlayerCameraLookAt(i,CPSpawn[Current][0],CPSpawn[Current][1],CPSpawn[Current][2]);
	    	   		SetPlayerCameraPos(i,CPSpawn[Current][0],CPSpawn[Current][1]-100,CPSpawn[Current][2]+80);
				}
			}

			new iString[140];
			format(iString,sizeof(iString),"~l~~h~Base starting in %s~h~%d ~l~~h~seconds~n~", TDC[Player[i][Team]], ViewTimer);
			PlayerTextDrawSetString(i, RoundText[i], iString);
		}
	}

	return SetTimer("ViewBaseForPlayers", 1000, false);
}

SpawnPlayersInBase()
{
	foreach(new i : Player) {
        PlayerTextDrawHide(i, RoundText[i]);

	    if(Player[i][Team] == ATTACKER || Player[i][Team] == DEFENDER) {
	        Player[i][Playing] = true;
	        Player[i][WasInBase] = true;
			Player[i][RoundKills] = 0;
			Player[i][RoundDeaths] = 0;
			Player[i][RoundDamage] = 0;

			PlayerPlaySound(i, 1057, 0, 0, 0);
			SetCameraBehindPlayer(i);

			SetPlayerArmour(i, 100);
			SetPlayerHealth(i, 100);

			SetPlayerScore(i, 200);
			
			switch(Player[i][Team]) {
			    case ATTACKER: {
			        SetSpawnInfo(i, Player[i][Team], Skin[Player[i][Team]], AttackerSpawn[Current][0] + random(6), AttackerSpawn[Current][1] + random(6), AttackerSpawn[Current][2], 0, 0, 0, 0, 0, 0, 0);
			        SetPlayerColor(i, ATTACKER_PLAYING);
           			SetPlayerMapIcon(i, 59, AttackerSpawn[Current][0], AttackerSpawn[Current][1], AttackerSpawn[Current][2], 59, 0, MAPICON_GLOBAL);
                    PlayersAlive[ATTACKER]++;
                    TeamHP[ATTACKER] = TeamHP[ATTACKER] + 200;
                    SAMP_SetPlayerTeam(i, ATTACKER);
				} case DEFENDER: {
			        SetSpawnInfo(i, Player[i][Team], Skin[Player[i][Team]], DefenderSpawn[Current][0] + random(6), DefenderSpawn[Current][1] + random(6), DefenderSpawn[Current][2], 0, 0, 0, 0, 0, 0, 0);
			        SetPlayerColor(i, DEFENDER_PLAYING);
			        PlayersAlive[DEFENDER]++;
			        TeamHP[DEFENDER] = TeamHP[DEFENDER] + 200;
			        SAMP_SetPlayerTeam(i, DEFENDER);
				} case REFEREE: {
			        SetSpawnInfo(i, Player[i][Team], Skin[Player[i][Team]], CPSpawn[Current][0] + random(6), CPSpawn[Current][1] + random(6), CPSpawn[Current][2], 0, 0, 0, 0, 0, 0, 0);
			        SetPlayerColor(i, REFEREE_COLOR);
			        SAMP_SetPlayerTeam(i, REFEREE);
				}
			}

			Player[i][IgnoreSpawn] = true;
			SpawnPlayerEx(i);

			TogglePlayerControllable(i, true);
			ShowPlayerWeaponMenu(i, Player[i][Team]);
			
			new iString[160];
			format(iString, sizeof(iString), "~n~~n~~l~~h~Kills %s~h~%d~n~~l~~h~Damage %s~h~%.0f~n~~l~~h~Total Dmg %s~h~%.0f", TDC[Player[i][Team]], Player[i][RoundKills], TDC[Player[i][Team]], Player[i][RoundDamage], TDC[Player[i][Team]], Player[i][TotalDamage]);
			PlayerTextDrawSetString(i, RoundKillDmgTDmg[i], iString);
		}
	}

	ClearChat();

	

	RoundMints = ConfigRoundTime;
	RoundSeconds = 0;

	TextDrawShowForAll(RoundStats);

	AllowStartBase = true;
	BaseStarted = true;
	
	RadarFix();
}


ShowPlayerWeaponMenu(playerid, team)
{
	ResetPlayerWeapons(playerid);

	new WepStr[2][350], WepTStr[700];
	switch(team) {
	    case ATTACKER: {
			format(WepStr[0], sizeof(WepStr[]), "{FF0000}ID\tPrimary Weapon\tSecondary Weapon\tAvailibility\n{FF3333}1\tM4\t\t\tMP5\t\t\t%d\n{FF6666}2\tM4\t\t\tShotgun\t\t%d\n{FF3333}3\tSniper Rifle\t\tShotgun\t\t%d\n{FF6666}4\tCountry Rifle\t\tShotgun\t\t%d\n{FF3333}5\tDesert Eagle\t\tMP5\t\t\t%d",WeaponLimit[0] - TimesPicked[ATTACKER][0] ,WeaponLimit[1] - TimesPicked[ATTACKER][1],WeaponLimit[2] - TimesPicked[ATTACKER][2],WeaponLimit[3] - TimesPicked[ATTACKER][3],WeaponLimit[4] - TimesPicked[ATTACKER][4]);
			format(WepStr[1], sizeof(WepStr[]), "\n{FF6666}6\tDesert Eagle\t\tAK-47\t\t\t%d\n{FF3333}7\tDesert Eagle\t\tShotgun\t\t%d\n{FF6666}8\tDesert Eagle\t\tCountry Rifle\t\t%d\n{FF3333}9\tCombat Shotgun\tCountry Rifle\t\t%d\n{FF6666}10\tCombat Shotgun\tSilenced 9mm\t\t%d",WeaponLimit[5] - TimesPicked[ATTACKER][5],WeaponLimit[6] - TimesPicked[ATTACKER][6],WeaponLimit[7] - TimesPicked[ATTACKER][7],WeaponLimit[8] - TimesPicked[ATTACKER][8],WeaponLimit[9] - TimesPicked[ATTACKER][9]);
			format(WepTStr, sizeof(WepTStr), "%s%s", WepStr[0], WepStr[1]);
 			ShowPlayerDialog(playerid, DIALOG_WEAPONS_TYPE, DIALOG_STYLE_LIST, "{FF0000}Select your weapon set:",WepTStr, "Select", "Exit");
		} case DEFENDER: {
			format(WepStr[0], sizeof(WepStr[]), "{0000FF}ID\tPrimary Weapon\tSecondary Weapon\tAvailibility\n{3333FF}1\tM4\t\t\tMP5\t\t\t%d\n{6666FF}2\tM4\t\t\tShotgun\t\t%d\n{3333FF}3\tSniper Rifle\t\tShotgun\t\t%d\n{6666FF}4\tCountry Rifle\t\tShotgun\t\t%d\n{3333FF}5\tDesert Eagle\t\tMP5\t\t\t%d",WeaponLimit[0] - TimesPicked[DEFENDER][0] ,WeaponLimit[1] - TimesPicked[DEFENDER][1],WeaponLimit[2] - TimesPicked[DEFENDER][2],WeaponLimit[3] - TimesPicked[DEFENDER][3],WeaponLimit[4] - TimesPicked[DEFENDER][4]);
			format(WepStr[1], sizeof(WepStr[]), "\n{6666FF}6\tDesert Eagle\t\tAK-47\t\t\t%d\n{3333FF}7\tDesert Eagle\t\tShotgun\t\t%d\n{6666FF}8\tDesert Eagle\t\tCountry Rifle\t\t%d\n{3333FF}9\tCombat Shotgun\tCountry Rifle\t\t%d\n{6666FF}10\tCombat Shotgun\tSilenced 9mm\t\t%d",WeaponLimit[5] - TimesPicked[DEFENDER][5],WeaponLimit[6] - TimesPicked[DEFENDER][6],WeaponLimit[7] - TimesPicked[DEFENDER][7],WeaponLimit[8] - TimesPicked[DEFENDER][8],WeaponLimit[9] - TimesPicked[DEFENDER][9]);
			format(WepTStr, sizeof(WepTStr), "%s%s", WepStr[0], WepStr[1]);
			ShowPlayerDialog(playerid, DIALOG_WEAPONS_TYPE, DIALOG_STYLE_LIST, "{0000FF}Select your weapon set:",WepTStr, "Select", "Exit");
		}
	}
}



EndRound(WinID) //WinID: 0 = CP, 1 = RoundTime, 2 = NoAttackersLeft, 3 = NoDefendersLeft
{
	BaseStarted = false;
    ClearKillList(); // Clears the kill-list.

	new Float:TopDamage[3], TopDamageIDs[3], iString[256];
	for(new i = 0; i < 3; i++) {
	    TopDamage[i] = 0;
	    TopDamageIDs[i] = -1;
	}
	TextDrawHideForAll(RoundStats);

	if(WinID == 0 || WinID == 3) {
		format(iString, sizeof(iString), "~n~~l~~h~%s Won", TeamName[ATTACKER]);
		if(WarMode == true) TeamScore[ATTACKER]++;
	} else if(WinID == 1 || WinID == 2) {
		format(iString, sizeof(iString), "~n~~l~~h~%s Won", TeamName[DEFENDER]);
		if(WarMode == true) TeamScore[DEFENDER]++;
	}
	TextDrawSetString(EN_WhoWon, iString);

	if(WarMode == true) {
		CurrentRound++;
		format(iString, sizeof(iString), "~l~~h~Rounds ~r~~h~%d~l~~h~/~r~~h~%d", CurrentRound, TotalRounds);
		TextDrawSetString(RoundsPlayed, iString);
	}
	
	
	SendRconCommand("mapname Lobby");
	Current = -1;

	new
	    playerScores[MAX_PLAYERS][rankingEnum],
	    index,
	    p
	;

	foreach(new i : Player) {
		if(Player[i][WasInBase] == true) {
			playerScores[index][player_Score] = floatround(Player[i][RoundDamage], floatround_round);
		    playerScores[index++][player_ID] = i;
		    p++;
		}

		Player[i][Playing] = false;
		Player[i][WasInCP] = false;
		if(Player[i][Spectating] == true) StopSpectate(i);
		Player[i][WasInBase] = false;
		
		SetSpawnInfo(i, GetPlayerTeam(i), Skin[Player[i][Team]], MainSpawn[0]+random(5),MainSpawn[1]+random(5),MainSpawn[2], MainSpawn[3], 0, 0, 0, 0, 0, 0);
		SetPlayerInterior(i,MainInterior);
		Player[i][IgnoreSpawn] = true;
		SpawnPlayer(i);

		DisablePlayerCheckpoint(i);
		SetPlayerScore(i, 0);
		
		ShowEndRoundTextDraw(i);
		
//	 	SetPlayerVirtualWorld(i, (i + 50));
		SetPlayerCameraLookAt(i,1660.3087,-2668.6558,16.5469);
   		SetPlayerCameraPos(i,1658.0651,-2668.4104,16.5469);


	}
	GetPlayerHighestScores(playerScores, 0, index-1);
	
	new AttList[256], AttKills[256], AttDeaths[256], AttDamage[256], DefList[256], DefKills[256], DefDeaths[256], DefDamage[256];
	for(new i = 0; i != p; ++i) {
	    if(Player[playerScores[i][player_ID]][Team] == ATTACKER) {
	        format(AttList, sizeof(AttList), "%s~l~~h~%s~n~", AttList, Player[playerScores[i][player_ID]][NameWithoutTag]);
		    format(AttKills, sizeof(AttKills), "%s~l~~h~%d~n~", AttKills, Player[playerScores[i][player_ID]][RoundKills]);
	        format(AttDeaths, sizeof(AttDeaths), "%s~l~~h~%d~n~", AttDeaths, Player[playerScores[i][player_ID]][RoundDeaths]);
	        format(AttDamage, sizeof(AttDamage), "%s~l~~h~%d~n~", AttDamage, playerScores[i][player_Score]);
		} else if(Player[playerScores[i][player_ID]][Team] == DEFENDER) {
	        format(DefList, sizeof(DefList), "%s~l~~h~%s~n~", DefList, Player[playerScores[i][player_ID]][NameWithoutTag]);
	        format(DefKills, sizeof(DefKills), "%s~l~~h~%d~n~", DefKills, Player[playerScores[i][player_ID]][RoundKills]);
	        format(DefDeaths, sizeof(DefDeaths), "%s~l~~h~%d~n~", DefDeaths, Player[playerScores[i][player_ID]][RoundDeaths]);
	        format(DefDamage, sizeof(DefDamage), "%s~l~~h~%d~n~", DefDamage, playerScores[i][player_Score]);
		}
	}
	TextDrawSetString(EN_AttackerList, AttList);
	TextDrawSetString(EN_AttackerKills, AttKills);
	TextDrawSetString(EN_AttackerDeaths, AttDeaths);
	TextDrawSetString(EN_AttackerDamage, AttDamage);
	TextDrawSetString(EN_DefenderList, DefList);
	TextDrawSetString(EN_DefenderKills, DefKills);
	TextDrawSetString(EN_DefenderDeaths, DefDeaths);
	TextDrawSetString(EN_DefenderDamage, DefDamage);

	
	foreach(new i : Player) {
	    if(Player[i][RoundDamage] > TopDamage[0]) {
		    TopDamage[0] = Player[i][RoundDamage];
		    TopDamageIDs[0] = i;
		}
	} foreach(new i : Player) {
	    if(Player[i][RoundDamage] > TopDamage[1] && i != TopDamageIDs[0]) {
	        TopDamage[1] = Player[i][RoundDamage];
	        TopDamageIDs[1] = i;
		}
	} foreach(new i : Player) {
		if(Player[i][RoundDamage] > TopDamage[2] && i != TopDamageIDs[0] && i != TopDamageIDs[1]) {
		    TopDamage[2] = Player[i][RoundDamage];
		    TopDamageIDs[2] = i;
		}
	}

	SendClientMessageToAll(-1, " ");
	SendClientMessageToAll(-1, " ");
	SendClientMessageToAll(-1, " ");
	SendClientMessageToAll(-1, " ");

	if(IsPlayerConnected(TopDamageIDs[0]) && !IsPlayerConnected(TopDamageIDs[1]) && !IsPlayerConnected(TopDamageIDs[2])) {
		SendClientMessageToAll(-1, "{888888}~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
		SendClientMessageToAll(-1, "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{888888}Top Players");
        SendClientMessageToAll(-1, " ");
		format(iString, sizeof(iString), "{888888}1st   -   %s   	({FFFFFF}%.0f{888888})", Player[TopDamageIDs[0]][Name], TopDamage[0]);
		SendClientMessageToAll(-1, iString);
		SendClientMessageToAll(-1, " ");
		SendClientMessageToAll(-1, "{888888}~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
	} else if(IsPlayerConnected(TopDamageIDs[0]) && IsPlayerConnected(TopDamageIDs[1]) && !IsPlayerConnected(TopDamageIDs[2])) {
		SendClientMessageToAll(-1, "{888888}~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
		SendClientMessageToAll(-1, "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{888888}Top Players");
        SendClientMessageToAll(-1, " ");
		format(iString, sizeof(iString), "{888888}1st   -   %s   	({FFFFFF}%.0f{888888})",Player[TopDamageIDs[0]][Name], TopDamage[0]);
		SendClientMessageToAll(-1, iString);
		format(iString, sizeof(iString), "{888888}2nd   -   %s   	({FFFFFF}%.0f{888888})",Player[TopDamageIDs[1]][Name], TopDamage[1]);
		SendClientMessageToAll(-1, iString);
		SendClientMessageToAll(-1, " ");
		SendClientMessageToAll(-1, "{888888}~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
	} else if(IsPlayerConnected(TopDamageIDs[0]) && IsPlayerConnected(TopDamageIDs[1]) && IsPlayerConnected(TopDamageIDs[2])) {
		SendClientMessageToAll(-1, "{888888}~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
		SendClientMessageToAll(-1, "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{888888}Top Players");
        SendClientMessageToAll(-1, " ");
		format(iString, sizeof(iString), "{888888}1st   -   %s   	({FFFFFF}%.0f{888888})",Player[TopDamageIDs[0]][Name], TopDamage[0]);
		SendClientMessageToAll(-1, iString);
		format(iString, sizeof(iString), "{888888}2nd   -   %s   	({FFFFFF}%.0f{888888})",Player[TopDamageIDs[1]][Name], TopDamage[1]);
		SendClientMessageToAll( -1, iString);
		format(iString, sizeof(iString), "{888888}3rd   -   %s   	({FFFFFF}%.0f{888888})",Player[TopDamageIDs[2]][Name], TopDamage[2]);
		SendClientMessageToAll(-1, iString);
		SendClientMessageToAll( -1, " ");
		SendClientMessageToAll( -1, "{888888}~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
	}
	
	if(CurrentRound >= TotalRounds && CurrentRound != 0) {
		SetTimer("WarEnded", 4000, 0);
		SendClientMessageToAll(-1, "{FFFFFF}>> {888888}Preparing End Match Results..");
		SendClientMessageToAll(-1, "{FFFFFF}>> {888888}If you missed the results screen by hiding the current textdraws, type {FFFFFF}/showagain.");
	}

	    


	return 1;
}

forward WarEnded();
public WarEnded()
{
    ClearKillList(); // Clears the kill-list.

	new Float:TopDamage[3], TopDamageIDs[3], iString[256];
	for(new i = 0; i < 3; i++) {
	    TopDamage[i] = 0;
	    TopDamageIDs[i] = -1;
	}
	
    TeamName[ATTACKER] = "Alpha";
    TeamName[DEFENDER] = "Beta";
    TeamScore[ATTACKER] = 0;
    TeamScore[DEFENDER] = 0;
    CurrentRound = 0;

	WarMode = false;

	format(iString, sizeof(iString), "~r~~h~%s ~l~~h~(%d)  ~b~~h~%s ~l~~h~(%d)",TeamName[ATTACKER],TeamScore[ATTACKER],TeamName[DEFENDER],TeamScore[DEFENDER]);
    TextDrawSetString(TeamScoreText, iString);

	format(iString, sizeof(iString), "~l~~h~Rounds ~r~~h~%d~l~~h~/~r~~h~%d", CurrentRound, TotalRounds);
	TextDrawSetString(RoundsPlayed, iString);

	iString = "password 0";
	SendRconCommand(iString);
	
	new
	    playerScores[MAX_PLAYERS][rankingEnum],
	    index,
	    p
	;

	foreach(new i : Player) {
		if(Player[i][TotalDamage] > 0) {
			playerScores[index][player_Score] = floatround(Player[i][TotalDamage], floatround_round);
		    playerScores[index++][player_ID] = i;
		    p++;
		}
		if(Player[i][Spectating] == true) StopSpectate(i);

		ShowEndRoundTextDraw(i);
		SetPlayerCameraLookAt(i,1660.3087,-2668.6558,16.5469);
   		SetPlayerCameraPos(i,1658.0651,-2668.4104,16.5469);
	}
	GetPlayerHighestScores(playerScores, 0, index-1);

	new AttList[256], AttKills[256], AttDeaths[256], AttDamage[256], DefList[256], DefKills[256], DefDeaths[256], DefDamage[256];
	for(new i = 0; i != p; ++i) {
	    if(Player[playerScores[i][player_ID]][Team] == ATTACKER) {
	        format(AttList, sizeof(AttList), "%s~l~~h~%s~n~", AttList, Player[playerScores[i][player_ID]][NameWithoutTag]);
		    format(AttKills, sizeof(AttKills), "%s~l~~h~%d~n~", AttKills, Player[playerScores[i][player_ID]][TotalKills]);
	        format(AttDeaths, sizeof(AttDeaths), "%s~l~~h~%d~n~", AttDeaths, Player[playerScores[i][player_ID]][TotalDeaths]);
	        format(AttDamage, sizeof(AttDamage), "%s~l~~h~%d~n~", AttDamage, playerScores[i][player_Score]);
		} else if(Player[playerScores[i][player_ID]][Team] == DEFENDER) {
	        format(DefList, sizeof(DefList), "%s~l~~h~%s~n~", DefList, Player[playerScores[i][player_ID]][NameWithoutTag]);
	        format(DefKills, sizeof(DefKills), "%s~l~~h~%d~n~", DefKills, Player[playerScores[i][player_ID]][TotalKills]);
	        format(DefDeaths, sizeof(DefDeaths), "%s~l~~h~%d~n~", DefDeaths, Player[playerScores[i][player_ID]][TotalDeaths]);
	        format(DefDamage, sizeof(DefDamage), "%s~l~~h~%d~n~", DefDamage, playerScores[i][player_Score]);
		}
	}
	TextDrawSetString(EN_AttackerList, AttList);
	TextDrawSetString(EN_AttackerKills, AttKills);
	TextDrawSetString(EN_AttackerDeaths, AttDeaths);
	TextDrawSetString(EN_AttackerDamage, AttDamage);
	TextDrawSetString(EN_DefenderList, DefList);
	TextDrawSetString(EN_DefenderKills, DefKills);
	TextDrawSetString(EN_DefenderDeaths, DefDeaths);
	TextDrawSetString(EN_DefenderDamage, DefDamage);
	

    if(TeamScore[ATTACKER] > TeamScore[DEFENDER]) {
 		format(iString, sizeof(iString),"~l~~h~%s Won The Match~n~~l~~h~%s ~r~~h~%d		~l~~h~%s ~b~~h~%d", TeamName[ATTACKER], TeamName[ATTACKER], TeamScore[ATTACKER], TeamName[DEFENDER], TeamScore[DEFENDER]);
	} else if(TeamScore[DEFENDER] > TeamScore[ATTACKER]) {
	    format(iString,sizeof(iString),"~l~~h~%s Won The Match~n~~l~~h~%s ~r~~h~%d		~l~~h~%s ~b~~h~%d",TeamName[DEFENDER], TeamName[DEFENDER], TeamScore[DEFENDER], TeamName[ATTACKER], TeamScore[ATTACKER]);
	}
	TextDrawSetString(EN_WhoWon, iString);

	foreach(new i : Player) {
	    if(Player[i][TotalDamage] > TopDamage[0]) {
		    TopDamage[0] = Player[i][TotalDamage];
		    TopDamageIDs[0] = i;
		}
	} foreach(new i : Player) {
	    if(Player[i][TotalDamage] > TopDamage[1] && i != TopDamageIDs[0]) {
	        TopDamage[1] = Player[i][TotalDamage];
	        TopDamageIDs[1] = i;
		}
	} foreach(new i : Player) {
		if(Player[i][TotalDamage] > TopDamage[2] && i != TopDamageIDs[0] && i != TopDamageIDs[1]) {
		    TopDamage[2] = Player[i][TotalDamage];
		    TopDamageIDs[2] = i;
		}
	}


	SendClientMessageToAll(-1, " ");
	SendClientMessageToAll(-1, " ");
	SendClientMessageToAll(-1, " ");
	SendClientMessageToAll(-1, " ");

	if(IsPlayerConnected(TopDamageIDs[0]) && !IsPlayerConnected(TopDamageIDs[1]) && !IsPlayerConnected(TopDamageIDs[2])) {
		SendClientMessageToAll(-1, "{888888}~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
		SendClientMessageToAll(-1, "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{888888}Top Players");
        SendClientMessageToAll(-1, " ");
		format(iString, sizeof(iString), "{888888}1st   -   %s   	({FFFFFF}%.0f{888888})", Player[TopDamageIDs[0]][Name], TopDamage[0]);
		SendClientMessageToAll(-1, iString);
		SendClientMessageToAll(-1, " ");
		SendClientMessageToAll(-1, "{888888}~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
	} else if(IsPlayerConnected(TopDamageIDs[0]) && IsPlayerConnected(TopDamageIDs[1]) && !IsPlayerConnected(TopDamageIDs[2])) {
		SendClientMessageToAll(-1, "{888888}~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
		SendClientMessageToAll(-1, "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{888888}Top Players");
        SendClientMessageToAll(-1, " ");
		format(iString, sizeof(iString), "{888888}1st   -   %s   	({FFFFFF}%.0f{888888})",Player[TopDamageIDs[0]][Name], TopDamage[0]);
		SendClientMessageToAll(-1, iString);
		format(iString, sizeof(iString), "{888888}2nd   -   %s   	({FFFFFF}%.0f{888888})",Player[TopDamageIDs[1]][Name], TopDamage[1]);
		SendClientMessageToAll(-1, iString);
		SendClientMessageToAll(-1, " ");
		SendClientMessageToAll(-1, "{888888}~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
	} else if(IsPlayerConnected(TopDamageIDs[0]) && IsPlayerConnected(TopDamageIDs[1]) && IsPlayerConnected(TopDamageIDs[2])) {
		SendClientMessageToAll(-1, "{888888}~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
		SendClientMessageToAll(-1, "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{888888}Top Players");
        SendClientMessageToAll(-1, " ");
		format(iString, sizeof(iString), "{888888}1st   -   %s   	({FFFFFF}%.0f{888888})",Player[TopDamageIDs[0]][Name], TopDamage[0]);
		SendClientMessageToAll(-1, iString);
		format(iString, sizeof(iString), "{888888}2nd   -   %s   	({FFFFFF}%.0f{888888})",Player[TopDamageIDs[1]][Name], TopDamage[1]);
		SendClientMessageToAll( -1, iString);
		format(iString, sizeof(iString), "{888888}3rd   -   %s   	({FFFFFF}%.0f{888888})",Player[TopDamageIDs[2]][Name], TopDamage[2]);
		SendClientMessageToAll(-1, iString);
		SendClientMessageToAll( -1, " ");
		SendClientMessageToAll( -1, "{888888}~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
	}
	
	return 1;
}


SpectatePlayer(playerid, specid) {

	new OldSpecID = -1;

	if(Player[playerid][BeingSpeced] == true) {
		foreach(new i : Player) {
		    if(Player[i][Spectating] == true && Player[i][IsSpectatingID] == playerid) {
				StopSpectate(i);
			}
		}
	} else if (Player[playerid][Spectating] == true && specid != Player[playerid][IsSpectatingID]) {
	    OldSpecID = Player[playerid][IsSpectatingID];
	}


	TogglePlayerSpectating(playerid, 1);

	if(IsPlayerInAnyVehicle(specid)) {
	    PlayerSpectateVehicle(playerid, GetPlayerVehicleID(specid));
	} else {
		PlayerSpectatePlayer(playerid, specid);
	}
	SetPlayerVirtualWorld(playerid, GetPlayerVirtualWorld(specid));
	SetPlayerInterior(playerid, GetPlayerInterior(specid));

	new string[256], Float:aArmour, Float:aHealth;
	GetPlayerHealth(specid, aHealth);
	GetPlayerArmour(specid, aArmour);

	format(string,sizeof(string),"~l~~h~%s ~r~~h~%d~n~~l~~h~(~w~%.0f~l~~h~)  ~l~~h~(~r~~h~%.0f~l~~h~)~n~~l~~h~Ping ~r~~h~%d ~l~~h~FPS ~r~~h~%d~n~~l~~h~Packet-Loss ~r~~h~%.1f", Player[specid][Name], specid, aArmour, aHealth, GetPlayerPing(specid), Player[specid][FPS], GetPlayerPacketLoss(specid));
	PlayerTextDrawSetString(playerid, SpecText[0][playerid], string);
    PlayerTextDrawShow(playerid,SpecText[0][playerid]);

	format(string,sizeof(string),"~l~~h~Round Damage ~r~~h~%.0f~n~~l~~h~Total Damage ~r~~h~%.0f~n~~l~~h~%s",Player[specid][RoundDamage], Player[specid][TotalDamage], SpecWeapons(specid));
	PlayerTextDrawSetString(playerid, SpecText[1][playerid], string);
    PlayerTextDrawShow(playerid,SpecText[1][playerid]);

	Player[playerid][Spectating] = true;
	Player[playerid][IsSpectatingID] = specid;
	Player[specid][BeingSpeced] = true;

	PlayerTextDrawHide(playerid, RoundKillDmgTDmg[playerid]);

	if(Player[specid][Playing] == true && GameType == 0) {
	    SetPlayerCheckpoint(playerid, CPSpawn[Current][0], CPSpawn[Current][1], CPSpawn[Current][2],2);
	} 

	new WhoSpecing[2][256], SpecingMe;
	WhoSpecing[0] = "~l~~h~Spectating You...";

	if(OldSpecID != -1) {
	    foreach(new i : Player) {
	        if(Player[i][Spectating] == true && Player[i][IsSpectatingID] == OldSpecID) {
				SpecingMe++;

				if(SpecingMe <= 5) {
		        	format(WhoSpecing[0], 256, "%s~n~~r~- ~l~~h~%s ~r~%d", WhoSpecing[0], Player[i][NameWithoutTag], i);
				} else if (SpecingMe <= 10) {
				    format(WhoSpecing[1], 256, "%s~r~- ~l~~h~%s ~r~%d~n~", WhoSpecing[1], Player[i][NameWithoutTag], i);
				}
			}
		}
		if(SpecingMe > 0) {
			PlayerTextDrawSetString(OldSpecID, WhoSpec[0][OldSpecID], WhoSpecing[0]);
			PlayerTextDrawSetString(OldSpecID, WhoSpec[1][OldSpecID], WhoSpecing[1]);
		} else {
			PlayerTextDrawSetString(OldSpecID, WhoSpec[0][OldSpecID], " ");
			PlayerTextDrawSetString(OldSpecID, WhoSpec[1][OldSpecID], " ");
			Player[OldSpecID][BeingSpeced] = false;
		}
	}

	SpecingMe = 0;
    WhoSpecing[0] = "~l~~h~Spectating You...";
    WhoSpecing[1] = " ";

	foreach(new i : Player) {
	    OnPlayerStreamIn(playerid, i);
	    OnPlayerStreamIn(i, playerid);
	    
	    if(Player[i][Spectating] == true && Player[i][IsSpectatingID] == specid) {
			SpecingMe++;

			if(SpecingMe <= 5) {
	        	format(WhoSpecing[0], 256, "%s~n~~r~- ~l~~h~%s ~r~%d", WhoSpecing[0], Player[i][NameWithoutTag], i);
			} else if (SpecingMe <= 10) {
			    format(WhoSpecing[1], 256, "%s~r~- ~l~~h~%s ~r~%d~n~", WhoSpecing[1], Player[i][NameWithoutTag], i);
			}
		}
	}
	if(SpecingMe > 0) {
		PlayerTextDrawSetString(specid, WhoSpec[0][specid], WhoSpecing[0]);
		PlayerTextDrawSetString(specid, WhoSpec[1][specid], WhoSpecing[1]);
	} else {
		PlayerTextDrawSetString(specid, WhoSpec[0][specid], " ");
		PlayerTextDrawSetString(specid, WhoSpec[1][specid], " ");
		Player[specid][BeingSpeced] = false;
	}



    return 1;
}

StopSpectate(playerid) {
 	if(Player[playerid][BeingSpeced] == true) {
		foreach(new i : Player) {
			if(Player[i][Spectating] == true && Player[i][IsSpectatingID] == playerid) {
			    StopSpectate(i);
			}
		}
	}

	new specid = Player[playerid][IsSpectatingID];

	Player[playerid][Spectating] = false;
	Player[playerid][IsSpectatingID] = -1;
	Player[playerid][BeingSpeced] = false;

	PlayerTextDrawHide(playerid, SpecText[0][playerid]);
	PlayerTextDrawHide(playerid, SpecText[1][playerid]);

	PlayerTextDrawShow(playerid, RoundKillDmgTDmg[playerid]);

    TogglePlayerSpectating(playerid, 0);

	SetSpawnInfo(playerid, GetPlayerTeam(playerid), Skin[Player[playerid][Team]], MainSpawn[0]+random(5),MainSpawn[1]+random(5),MainSpawn[2], MainSpawn[3], 0, 0, 0, 0, 0, 0);
	SetPlayerInterior(playerid,MainInterior);
	Player[playerid][IgnoreSpawn] = true;
	SpawnPlayer(playerid);

	new WhoSpecing[2][254], SpecingMe = 0;
    WhoSpecing[0] = "~l~~h~Spectating You...";

	foreach(new i : Player) {
	    if(Player[i][Spectating] == true && Player[i][IsSpectatingID] == specid) {
			SpecingMe++;

			if(SpecingMe <= 5) {
	        	format(WhoSpecing[0], 256, "%s~n~~r~- ~l~~h~%s ~r~%d", WhoSpecing[0], Player[i][NameWithoutTag], i);
			} else if (SpecingMe <= 10) {
			    format(WhoSpecing[1], 256, "%s~r~- ~l~~h~%s ~r~%d~n~", WhoSpecing[1], Player[i][NameWithoutTag], i);
			}
		}
	}
	if(SpecingMe > 0) {
		PlayerTextDrawSetString(specid, WhoSpec[0][specid], WhoSpecing[0]);
		PlayerTextDrawSetString(specid, WhoSpec[1][specid], WhoSpecing[1]);
	} else {
		PlayerTextDrawSetString(specid, WhoSpec[0][specid], " ");
		PlayerTextDrawSetString(specid, WhoSpec[1][specid], " ");
		Player[specid][BeingSpeced] = false;
	}

	return 1;
}



stock SpectateNextTeamPlayer(playerid){
	new PAvailable = 0;

	foreach(new i : Player) {
	    if(Player[playerid][Team] == ATTACKER || Player[playerid][Team] == ATTACKER_SUB) {
	        if(Player[i][Team] == ATTACKER && i != playerid && Player[i][Playing] == true) PAvailable++;
		} else if(Player[playerid][Team] == DEFENDER || Player[playerid][Team] == DEFENDER_SUB) {
		    if(Player[i][Team] == DEFENDER && i != playerid && Player[i][Playing] == true) PAvailable++;
		}
	}

	if(PAvailable < 2 && Player[playerid][CalledByPlayer] == true){
		Player[playerid][CalledByPlayer] = false;
  		return 1;
	} else if(PAvailable < 1) {
	    StopSpectate(playerid);
		return 1;
	} else {
        Player[playerid][CalledByPlayer] = false;
	    new searching;
	    for(new i = Player[playerid][IsSpectatingID]+1; i <= HighestID+1; i++){
			if(searching > 1) {
				break;
			}
	    	if(i == HighestID+1) {
				i = 0;
	            searching++;
			}

			if(IsPlayerConnected(i) && i != playerid && Player[i][Playing] == true && Player[i][Team] != NON && GetPlayerState(i) != PLAYER_STATE_WASTED && IsTeamTheSame(Player[i][Team], Player[playerid][Team])) {
				SpectatePlayer(playerid, i);
			 	break;
			}
		}
	}
	return 1;
}

stock SpectatePreviousTeamPlayer(playerid) {
	new PAvailable = 0;

	foreach(new i : Player) {
	    if(Player[playerid][Team] == ATTACKER || Player[playerid][Team] == ATTACKER_SUB) {
	        if(Player[i][Team] == ATTACKER && i != playerid && Player[i][Playing] == true) PAvailable++;
		} else if(Player[playerid][Team] == DEFENDER || Player[playerid][Team] == DEFENDER_SUB) {
		    if(Player[i][Team] == DEFENDER && i != playerid && Player[i][Playing] == true) PAvailable++;
		}
	}

	if(PAvailable < 2 && Player[playerid][CalledByPlayer] == true){
		Player[playerid][CalledByPlayer] = false;
  		return 1;
	} else if(PAvailable < 1) {
	    StopSpectate(playerid);
		return 1;
	} else {
        Player[playerid][CalledByPlayer] = false;
	    new searching;
		for(new i = Player[playerid][IsSpectatingID]-1; i >= -1; i--) {
			if(searching > 1) {
			    break;
			}
			if(i < 0) {
				i = HighestID+1;
	            searching++;
			}

			if(IsPlayerConnected(i) && i != playerid && Player[i][Spectating] == false && Player[i][Playing] == true && Player[i][Team] != NON && GetPlayerState(i) != PLAYER_STATE_WASTED && IsTeamTheSame(Player[i][Team], Player[playerid][Team])) {
				SpectatePlayer(playerid, i);
				break;
			}
		}
	}
	return 1;
}

stock SpectateNextPlayer(playerid){
	new PAvailable = 0;

	foreach(new i : Player) {
	    if(Player[i][Team] != NON && Player[i][Spectating] == false) PAvailable++;
	}

	if(PAvailable < 2 && Player[playerid][CalledByPlayer] == true){
		Player[playerid][CalledByPlayer] = false;
  		return 1;
	} else if(PAvailable < 1) {
	    StopSpectate(playerid);
		return 1;
	} else {
        Player[playerid][CalledByPlayer] = false;
	    new searching;
	    for(new i = Player[playerid][IsSpectatingID]+1; i <= HighestID+1; i++){
			if(searching > 1) {
				break;
			}
	    	if(i == HighestID+1) {
				i = 0;
	            searching++;
			}

			if(IsPlayerConnected(i) && i != playerid && Player[i][Spectating] == false && Player[i][Team] != NON && GetPlayerState(i) != PLAYER_STATE_WASTED ) {
				SpectatePlayer(playerid, i);
			 	break;
			}
		}
	}
	return 1;
}

stock SpectatePreviousPlayer(playerid) {
	new PAvailable = 0;

	foreach(new i : Player){
	    if(Player[i][Team] != NON && Player[i][Spectating] == false) PAvailable++;
	}

	if(PAvailable < 2 && Player[playerid][CalledByPlayer] == true){
		Player[playerid][CalledByPlayer] = false;
  		return 1;
	} else if(PAvailable < 1) {
	    StopSpectate(playerid);
		return 1;
	} else {
        Player[playerid][CalledByPlayer] = false;
	    new searching;
		for(new i = Player[playerid][IsSpectatingID]-1; i >= -1; i--) {
			if(searching > 1) {
			    break;
			}
			if(i < 0) {
				i = HighestID+1;
	            searching++;
			}

        	if(IsPlayerConnected(i) && i != playerid && Player[i][Spectating] == false && Player[i][Team] != NON && GetPlayerState(i) != PLAYER_STATE_WASTED) {
				SpectatePlayer(playerid, i);
				break;
			}
		}
	}
	return 1;
}
